题目链接:https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
思路:
- 思路很直接,就是对容器中的每一个元素的每一个字符逐字符的遍历确认,直至出现不等的情况,则返回。
- 例如:对容器strs = ["flower","flow","flight"] 而言,具体操作为:
- 初始化令 index = 0, ch = strs[0][index], i = 1,返回结果ans = "";
- 如果 ch == strs[i][index] 则i++,继续循环判断上述条件是否成立,若对容器中的所有元素进行上述条件判断都满足,则该字符为公共前缀的字符之一,需要添加到ans变量中:
ans += strs[i-1][index];
- 否则 return ans(返回结果)。
- 注意:每次判断前要判断索引index的值是否大于当前要比较容器中元素的size。
编码如下:
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string>& strs) { 4 string ans = ""; 5 int index = -1; 6 7 if (strs.size() > 0) 8 { 9 while (++index >= 0) 10 { 11 int i = 0; 12 char ch; 13 14 if (index >= strs[i].size()) 15 break; 16 else 17 ch = strs[i][index]; 18 19 for (i = 1; i < strs.size(); ++i) 20 { 21 if (index >= strs[i].size()) 22 return ans; 23 24 if (ch == strs[i][index]) 25 { 26 continue; 27 } 28 else 29 { 30 return ans; 31 } 32 } 33 34 ans += strs[i-1][index]; 35 } 36 } 37 38 return ans; 39 } 40 };