Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created October 14, 2018 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/991f56aa6f916d21b84c103f60fae535 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/991f56aa6f916d21b84c103f60fae535 to your computer and use it in GitHub Desktop.
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len_s = strs.size();
if(len_s == 0) return "";
for(int j = 0; j < strs[0].size(); j++){
char c = strs[0][j];
for(int i = 0; i < len_s; i++){
//Basically we check two cases:
//1 The sub string i reaches its end, which means this should be the common prefix
//2 The current element is not equal to the common element any more
if(j == strs[i].size() || strs[i][j] != c)
return strs[0].substr(0, j);
}
}
return strs[0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment