首页 > 其他 > 详细

leetcode [14] - Longest Common Prefix

时间:2019-05-29 15:57:38      阅读:96      评论:0      收藏:0      [点我收藏+]

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.

题目大意:

  输入字符串数组,输出这些字符串的最大公共子串。

理  解 :

  用当前公共子串与其他字符串比较,保留两字符串的最大公共串作为当前公共串。

代  码 C++:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string commonStr;
        int n,i,j,len,lastLen;
        n = strs.size();
        if(n==0) return "";
        commonStr = strs[0];
        len = commonStr.length();
        lastLen = len;
        for(i=1;i<n;++i){
            if(commonStr==" ") return "";
            j = 0;
            while(commonStr[j]==strs[i][j] && commonStr[j]!=\0 && strs[i][j]!=\0){
                ++j;
            }
            lastLen = j;
            while(j<len){
                commonStr[++j] =  ;
            }
            commonStr[lastLen] = \0;
            len = lastLen;
        }
        return commonStr;
    }
};

 

leetcode [14] - Longest Common Prefix

原文:https://www.cnblogs.com/lpomeloz/p/10944234.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!