同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为给定多个字符串,寻找这些字符串中,前面相同的位元。
题目与范例如下
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
解题策略为透过index ,先检查index 有没有超过第一个字符串,如果没有则依序判断有没有超过其他字符串,与是否和第一个字串相同,假设不同或超过其他字符串长度则把第一个字符串该index 设为'\0' 代表结束,最后回传第一个字符串。
下方为我的代码
char * longestCommonPrefix(char ** strs, int strsSize){
int index = 0; // index control return index
while(index<strlen(strs[0])){
for(int i = 0;i<strsSize;i++){ // i control which str
if(index<strlen(strs[i])){
if(strs[0][index] == strs[i][index]){
}
else{
strs[0][index] = '\0';
return strs[0];
}
}
else{
strs[0][index] = '\0';
return strs[0];
}
}
index++;
}
return strs[0];
}
下方为时间与空间之消耗
Runtime: 0 ms, faster than 100 % of C online submissions for Longest Common Prefix.
Memory Usage: 5.7 MB, less than 97.7 % of C online submissions for Longest Common Prefix.