14. Longest Common Prefix

题目链接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 };

转载于:https://www.cnblogs.com/ming-1012/p/10005018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值