Longest Common Prefix -- Solution report
[Question]
Write a function to find the longest common prefix string amongst an array of strings.
[Analysis]
The public prefix indicates that all strings have the same prefix. Obviously, the length of the longest common prefix will not exceed the shorter of all strings.
We first obtain the shortest String Length minLen, and then traverse all strings to determine whether the first minLen is equal.
[Code]
Running time: 7 ms
class Solution {public: string longestCommonPrefix(vector
& strs) { if(strs.empty()) return ""; int minLen = strs[0].length(); for(int i = 0; i < strs.size(); i++) { minLen = minLen < strs[i].length() ? minLen : strs[i].length(); //minLen = min(minLen, strs[i].size()); // obtain the minimal length } string res = ""; bool same = true; for(int j = 0; same && j < minLen; j++) { for(int k = 1; k < strs.size(); k++) { if(strs[k][j] != strs[0][j]) { same = false; break; } } if(same) res = res + strs[0][j]; // after the loop, res should ++ } return res; }};