本文主要是介绍leetcode No14. Longest Common Prefix,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Question:
Write a function to find the longest common prefix string amongst an array of strings.
大意即是求字符串组的最长公共前缀
Ex:
vector<string> strs={"abc","abcd","abcdef"};
那么最长公共前缀即"abc";
Algorithm:
先找出最小长度的字符串长度,记为min_length,然后从第一个前缀开始往后找。
Accepted Code:
class Solution {
public:string longestCommonPrefix(vector<string>& strs) {string s;if(strs.empty())return "";if(strs.size()==1)return strs[0];int min_length = strs[0].size();int flag = 0; //作为一次循环的标志,如果每一个字符串相同位置的字符都相等flag=0for(int i=0;i<strs.size();i++){min_length<strs[i].size()?min_length:strs[i].size();}for(int j=0;j<min_length;j++){int tmp = strs[0][j];for(int i=1;i<strs.size();i++){if(strs[i][j] != tmp){flag = 1;break;}}if(flag == 0)s.push_back(tmp);}return s;}
};
这篇关于leetcode No14. Longest Common Prefix的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!