[LeetCode] Longest Common Prefix
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 ""; size_t size = strs[0].size(); size_t idx = 0; for(size_t i = 0; i < size; i++ ) { for(size_t j = 1; j < strs.size(); j++ ) { if(strs[j][i] != strs[0][i]) { return strs[0].substr(0,idx); } } idx ++; } return strs[0].substr(0,idx); } };