题解 | #最长公共前缀#

最长公共前缀

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

#include <string>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param strs string字符串vector
     * @return string字符串
     */
    static bool isINstring(string substring, string str) {

        if (substring == str.substr(0, substring.length())) {
            return true;
        }
        return false;
    }


    string longestCommonPrefix(vector<string>& strs) {
        // write code here
        int length = strs.size();
        unsigned int minLength = ~0, i = 0, minIndex = 0;
        while (i < length) {
            if (minLength > strs[i].length()) {
                minLength = strs[i].length();
                minIndex = i;
            }
            i++;
        }
        int end = minLength;
        string output = "";
        int maxld =0;
        while (end > 0) {
        for (i=0; i<strs.size(); i++) {
            if (i == minIndex) {
                if (strs.size() == 1) {
                    output = strs[minIndex];
                }else {
                    continue;
                }   
            }

                if(Solution::isINstring(strs[minIndex].substr(0,end), strs[i])){
                    if (maxld < strs[minIndex].substr(0,end).length()) {
                        output = strs[minIndex].substr(0,end);
                        maxld = strs[minIndex].substr(0,end).length();
                    } 
                }
                else {
                    maxld = 0;
                }
                
            }
            end--;
        }
        return output;
    }
};

全部评论
先找到最短的那个字符串,然后使用end标记最短字符串的尾部,长的字符串没有一致的就减少长度end--。同时设置maxld标记,一旦有一个字符串不相等立刻置零,让本次最大长度无效。
点赞 回复 分享
发布于 2024-08-18 01:39 江苏

相关推荐

10-27 02:29
已编辑
门头沟学院 嵌入式工程师
牛客72783561...:简历不是这么写的,你这两个项目只说了用到了什么技术,却没说取得了什么成果,在我看来这就是你自己做的一个demo,没有价值。你为什么不写你电赛国二的那个项目?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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