题解 | #最长公共前缀#

最长公共前缀

https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        // write code here 
        int n = strs.size();
        string s;
        if(n == 0 ) return s;
        if(n == 1) return strs[0];
        s = strs[0];
        int flag = 0;
        for(int i = 1; i < n; i++){
            string temp = strs[i];
            for(int j = 0; j< temp.size() && j < s.size(); j++){
                if(temp[j] == s[j]){
                    flag++;//用flag不断更新flag值
                }
                else  //方便提前退出循环
                  break;
                  
            }
        
          s = s.substr(0, flag );//substr(first, last)函数是截取first下面的元素而不包括last下面的元素                                  //所以不需要写当flag为0时的特殊情况,当flag为0时,本身就是空字符串
            flag = 0;
        }
        return s;

    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
爱吃烤肠的牛油最喜欢...:50K是ssp了估计,ssp的人家多厉害都不用说,每年比例大概在百分之5左右
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务