[LeetCode] Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
class Solution { public: string longestCommonPrefix(vector<string> &strs) { int len = 0, n = strs.size(), MaxL = 0; if(n == 0) return ""; else if(n == 1) return strs[0]; for(int i = 0;i < n;i++) if(strs[i].length() > MaxL) MaxL = strs[i].length(); bool flag = true; while(flag) { if(len >= MaxL) break; for(int i = 0;i < n;i++) { if(strs[i][len] == strs[0][len]) continue; else { flag = false; break; } } if(flag == true) len++; } return strs[0].substr(0, len); } };