Write a function to find the longest common prefix string amongst an array of strings.
class Solution { public: string longestCommonPrefix(vector<string>& strs) { string longestPrefix=""; int strsSize = strs.size(); if(strsSize==0) return longestPrefix; if(strsSize==1) return strs[0]; int shortestStringLength = strs[0].size(); for(int i=1;i<strsSize;i++) if(shortestStringLength>strs[i].size()) shortestStringLength = strs[i].size(); for(int i=0;i<shortestStringLength;i++) { for(int j=1;j<strsSize;j++) if(strs[j][i]!=strs[j-1][i]) return longestPrefix; longestPrefix+=strs[0][i]; } return longestPrefix; } };
No comments:
Post a Comment