[LeetCode] Longest Common Prefix
Use the strs[0] as the reference string and then compare it with the remaining strings from left to right. Once we find a string with length less than strs[0] or different letters in the corresponding position, we cannot move on and should return the longest common prefix string lcp. Each time we finish checking a position and have not returned, we add the letter at that position to lcp.
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string>& strs) { 4 if (strs.empty()) return ""; 5 string lcp = ""; 6 int m = strs.size(), n = strs[0].length(); 7 for (int i = 0; i < n; i++) { 8 for (int j = 1; j < m; j++) 9 if (strs[j].length() == i || strs[j][i] != strs[0][i]) 10 return lcp; 11 lcp += strs[0][i]; 12 } 13 return lcp; 14 } 15 };