最长公共前缀
描述:https://leetcode.cn/leetbook/read/array-and-string/ceda1/
错误代码
c语言代码⬇️
char * longestCommonPrefix(char ** strs, int strsSize){
char commonPre[201];
int idx = 0;
commonPre[idx] = '';
for(int j = 0; j < 201; j++){
if(strs[0][j] != '\0'){
for(int i = 1; i < strsSize; i++){
if(strs[i][j] != '\0' && strs[i][j] == strs[0][j]){
continue;
}
break;
}
if(i == strsSize){
commonPre[idx++] = strs[0][j];
}
continue;
}
break;
}
return commonPre;
}
错误原因:数组越界,哪越界了?我气死
数组越界代码↓
char * longestCommonPrefix(char ** strs, int strsSize){
char commonPre[201];
int idx = 0;
int j = 0;
while(strs[0][j] != '\0'){
int i;
for(i = 1; i < strsSize; i++){
if(strs[i][j] != '\0' && strs[i][j] == strs[0][j]){
continue;
}
break;
}
if(i == strsSize){
commonPre[idx++] = strs[0][j];
}
j++;
}
commonPre[idx] = '\0';
return commonPre;
}
不越界错误代码↓
char * longestCommonPrefix(char ** strs, int strsSize){
char commonPre[201];
int idx = 0;
int j = 0;
while(strs[0][j] != '\0'){
int i;
for(i = 1; i < strsSize; i++){
if(strs[i][j] != '\0' && strs[i][j] == strs[0][j]){
continue;
}
break;
}
if(i == strsSize){
commonPre[idx++] = strs[0][j];
}else{
break;//区别在这里!
}
j++;
}
commonPre[idx] = '\0';
return commonPre;
}
错误原因:如果不在发现最长公共前缀后停下来(及时地打断while循环),可能会发生
S1:apple
S2:app
S3:applepen
在第5次while循环时,依次比较s1,s2,s3的第5个字符,而s2没有第5个字符,此时发生数组越界。
如果在比较之前,先对数组排序,短前长后,则同样的处理方式,不会发生数组越界。
错误代码2↓
char * longestCommonPrefix(char ** strs, int strsSize){
char commonPre[201];
int idx = 0;
int j = 0;
while(strs[0][j] != '\0'){
int i;
for(i = 1; i < strsSize; i++){
if(strs[i][j] != strs[0][j]){
break;;
}
}
if(i == strsSize){
commonPre[idx++] = strs[0][j];
}else{
break;
}
j++;
}
commonPre[idx] = '\0';
return commonPre;
}
通过代码
通过代码1⬇️
char* longestCommonPrefix(char** strs, int strsSize) {
char* commonPre;
commonPre = (char*)malloc(sizeof(char) * 201);
int idx = 0;
int j = 0;
while (strs[0][j] != '\0') {
int i = 0;
for (i = 1; i < strsSize; i++) {
if (strs[i][j] != strs[0][j]) {
break;
}
}
if (i == strsSize) {
commonPre[idx++] = strs[0][j];
}
else {
break;
}
j++;
}
commonPre[idx] = '\0';
return commonPre;
}
通过代码2⬇️
总结
总结:在函数中创建的数组,在函数调用完成之后会释放空间, 所以如果想要保存在函数中的工作,尽量创建一个指针变量,开辟出一片空间,返回的时候返回指针,这样就可以保存函数所做的工作。
如此就不会返回null了。