Write a function to find the longest common prefix string amongst an array of strings.
求若干字符串的最长公共前缀。
首先若无字符串,返回“”;接下来求得其中最短字符串的长度len,比较公共前缀只需最多比较len次;最后比较所有字符串里每一位上的字符。
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if(strs.size() == 0) return ""; //if(strs.size() == 1) //return strs[0]; int len = strs[0].length(); for(int i = 1; i < strs.size(); i++) { if(len > strs[i].length()) len = strs[i].length(); } if(len == 0) return ""; int i = 0; int j = 1; bool a = true; while(i<len && a) { for(j = 1; j < strs.size(); j++) { if(strs[j][i] != strs[j-1][i]) { a = false; break; } } if(j == strs.size()) { i++; } } return strs[0].substr(0, i); } };
Leetcode25: Longest Common Prefix
原文地址:http://blog.csdn.net/u013089961/article/details/45582513