c语言复试机试
时间: 2025-04-20 14:37:21 浏览: 17
### C语言面试机试常见题目及解法
#### 寻找相同子串
在一个字符串中查找两个指定位置之间的最长公共子串长度。给定两个起始索引和结束索引,计算这两个区间内的最大重复字符序列。
```c
#include <stdio.h>
#include <string.h>
int findLongestCommonSubstring(const char *str, int start1, int end1, int start2, int end2) {
int maxLength = 0;
for (int i = start1; i <= end1; ++i) {
for (int j = start2; j <= end2; ++j) {
int length = 0;
while ((i + length <= end1) && (j + length <= end2) && str[i + length] == str[j + length]) {
++length;
}
if (length > maxLength) {
maxLength = length;
}
}
}
return maxLength;
}
void test() {
const char* s = "abcdeabcdex";
printf("%d\n", findLongestCommonSubstring(s, 0, strlen(s)-1, 5, strlen(s)-1));
}
```
此函数遍历所有可能的起点组合并记录遇到的最大匹配长度[^1]。
#### 符号运算
实现一个简单的表达式求值器来处理加减乘除四则运算以及括号优先级。该算法通常采用栈结构存储操作符与数值,在读取到右括号或其他终止条件时弹出执行相应算术操作。
```c
#include <ctype.h>
#include <stdlib.h>
#define MAXOP 100 /* max size of operand or operator */
#define NUMBER '0'/* signal that a number was found */
int getop(char []);
void push(double);
double pop(void);
// Evaluate arithmetic expression with precedence handling using stack.
main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch(type){
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop()-op2);
break;
case '/':
op2 = pop();
if(op2 != 0.0)
push(pop()/op2);
else
printf("error: zero divisor\n");
break;
case '\n':
printf("\t%.8g\n",pop());
break;
default :
printf("error: unknown command %s\n",s);
break;
}
}
return 0;
}
```
上述程序展示了如何利用堆栈机制解决带有括号嵌套关系的基础数学表达式的即时评估问题[^2].
#### 找车位
对于停车场布局优化的问题,可以通过线性扫描的方法找出最优停车位的位置。具体做法是从左至右依次考察每一个空闲格子作为候选方案,并维护当前已知的最佳选项直到遍历完成为止。
```c
#include <limits.h>
int parking(int slots[], int n) {
int prevEmptyIndex=-1,maxDist=INT_MIN,optimalPosition=-1;
for (int i=0;i<n;++i){
if(slots[i]==0){ // 当前位置为空位
int dist=(prevEmptyIndex==-1)?i:(i-prevEmptyIndex)/2;
if(dist>maxDist || (dist==maxDist&&optimalPosition<0)){
optimalPosition=i;
maxDist=dist;
}
prevEmptyIndex=i;
}else{ // 更新最后一个看到的非空位下标
continue;
}
}
// 处理最后一段连续空位的情况
if(n-1-prevEmptyIndex>=maxDist){
optimalPosition=n-1;
}
return optimalPosition;
}
```
这段代码实现了寻找最佳停车位置的功能,确保所选地点远离其他车辆以减少潜在碰撞风险[^4].
阅读全文
相关推荐




















