[LeetCode]Longest Common Prefix

来源:互联网 发布:紫微斗数排盘软件 编辑:程序博客网 时间:2024/05/04 15:09

Write a function to find the longest common prefix string amongst an array of strings.


class Solution {public:    string longestCommonPrefix(vector<string> &strs)     {std::string ans("");//字符串数组为空if(strs.size()==0){return ans;}//字符串数组大小为1if(strs.size() == 1){return strs[0];}//字符串数组大小大于1int count = 0;//j用来表示列,i用来表示第几个字符串for (int j = 0; j < INT_MAX; j++){std::vector<char> result;for (int i = 0; i < strs.size(); i++){if(j < strs[i].size() && strs[i].size() != 0){//各个字符串的j列都和第0个字符串的j列比较if (strs[i][j]==strs[0][j]&&strs[i][j] != '\0'){result.push_back(strs[i][j]);}  else{break;}}}//若j列都相同,则count++;有一个不同,则停止比较if (result.size() == strs.size()){count++;}else{j = INT_MAX - 1;break;}}if (count >= 0){for (int i = 0; i < count; i++){ans = ans + strs[0][i];}}return ans;    }};


0 0
原创粉丝点击