14. 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.

翻译:
编写一个函数来查找字符串数组中最长的公共前缀字符串。 如果没有公共前缀,则返回空字符串“”。
例1:

Input: ["flower","flow","flight"]
Output: "fl"

例2:

Input: ["dog","racecar","car"]
Output: ""
说明: 输入的字符串中没有公共的前缀.

注意:
所有给定的输入都是小写字母a-z.

C++代码:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string prefix = "";
        int num=0;
        if(strs.empty())return prefix;//对空输入的处理
        int shortestlen=strs[0].length();
        
        for(int i=1;i<strs.size();i++)//获取数组中最短字符串的长度
        {
            if(shortestlen>strs[i].length())shortestlen=strs[i].length();    
        }
        
        for(num=0;num<shortestlen;num++)  //从字符串左侧遍历      以最短字符串长度为基准   
        {
            int right=1;
            for(int i=0;i<strs.size();i++)//循环字符串数组  遍历数组中字符串相同位置字母是否相同   如有不同则标志位right置0跳出循环
            {
                if(strs[0][num]!=strs[i][num]){right=0;break;}
            } 
            if(right==0) break;
        }
        
        for(int j=0;j<num;j++)//根据长度num将字符添加到字符串上
        {
            prefix+=strs[0][j]; 
        }
        return prefix;
    }
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值