Write a function to find the longest common prefix string amongst an array of strings.
题意:求字符串数组的最长公共前缀
思路:首先找到最短的那个作为标尺,然后每次比较。
class Solution { public: string longestCommonPrefix(vector<string> &strs) { if (strs.size() == 0) return ""; int index = 0; for (int i = 0; i < strs.size(); i++) if (strs[i].size() < strs[index].size()) index = i; int ans = strs[index].size(); for (int i = 0; i < strs.size(); i++) { if (i == index) continue; int tmp = 0; for (int j = 0; j < strs[i].size() && j < ans; j++) { if (strs[i][j] == strs[index][j]) tmp++; else break; } ans = tmp; } return strs[index].substr(0, ans); } };
LeetCode Longest Common Prefix
原文:http://blog.csdn.net/u011345136/article/details/43061829