[LeetCode] Longest Common Prefix

14. Longest Common Prefix

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 “”.

  • Time : O(k * min(length of str))
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int index = 0, target, find = 1;
for(; find ; index++) {
for(target = 0; target <= strs.size(); target++) {
if(strs[target].length() == index) {find = 0; break;}
if(strs[target][index] != strs[0][index]) {find = 0; break;}
}
}
return strs[target].substr(0,index-1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/longest-common-prefix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.