标签:longest common prefi leetcode algorithm 面试 最长公共前缀
Write a function to find the longest common prefix string amongst an array of strings.
给一个字符串数组,求这些字符串的最长公共前缀。
这个题应该是比较简单的,直接写代码,一次AC。解题思想是依次对数组中的字符串求最长公共前缀。
class Solution { public: string longestCommonPrefix(vector<string> &strs) { int n = strs.size(); string ret; if(n <=0) return ret; ret = strs[0]; for(int i=1; i<n; ++i){ commonPrefix(ret, strs[i]); } return ret; } void commonPrefix(string &ret, const string &s2){ int n = ret.size(); int m = s2.size(); int i=0; while(i<n && i<m){ if(ret[i] != s2[i]) break; ++i; } ret = ret.substr(0, i); } };
[ LeetCode ] Longest Common Prefix,布布扣,bubuko.com
[ LeetCode ] Longest Common Prefix
标签:longest common prefi leetcode algorithm 面试 最长公共前缀
原文地址:http://blog.csdn.net/swagle/article/details/28401133