题解 | #最长公共前缀#

最长公共前缀

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

#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param strs string字符串vector 
     * @return string字符串
     */
    string longestCommonPrefix(vector<string>& strs) {
        // write code here
        int n=strs.size();
        if(n==0)
            return "";
        else if(n==1){
            return strs[0];
        }
        vector<int> dp(n, 9999);
        for(int i=1;i<n;i++){
            dp[i] = min(com(strs[i-1],strs[i]), dp[i-1]);
        }
        return strs[0].substr(0, dp[n-1]);
    }

    int com(string s1,string s2){
        if(s1.size()==0|| s2.size()==0){
            return 0;
        }else{
            int res=0;
            int n = min(s1.size(),s2.size());
            for(int j=0;j<n;j++){
                if(s1[j] == s2[j]){
                    res++;
                }else{
                    break;
                }
            }
            return res;
        }
    }
};

全部评论

相关推荐

05-09 13:22
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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