本文主要是介绍leetcode 刷题之路 8 Longest Common Prefix,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Write a function to find the longest common prefix string amongst an array of strings.寻找一组字符串的最长公共前缀,比较简单,直接贴上程序:
accepted answer:
class Solution {
public:string longestCommonPrefix(vector<string> &strs) {string prefix;if (strs.empty()) return "";prefix = strs[0];for (int i = 0; i < strs.size(); i++){int len1 = prefix.length();int len2 = prefix.length();int j = 0;while (j < len1&&j < len2&&prefix[j] == strs[i][j]) j++;prefix = prefix.substr(0, j);}return prefix; }
};
这篇关于leetcode 刷题之路 8 Longest Common Prefix的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!