题解 | #最长公共前缀#

最长公共前缀

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

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param strs string字符串一维数组
     * @return string字符串
     */
    public string longestCommonPrefix (List<string> strs) {
        // write code here
        if (strs == null)
            return null;
        if (strs.Count == 0)
            return string.Empty;
        if (strs.Count == 1)
            return strs[0];

        string strMin = strs[0];
        for (int nIndex = 1; nIndex < strs.Count; nIndex++) {
            if (strs[nIndex].Length >= strMin.Length)
                continue;
            else
                strMin = strs[nIndex];
        }
        if (string.IsNullOrWhiteSpace(strMin))
            return "";
        string strRtn = string.Empty;
        for (int nIndex = strMin.Length - 1; nIndex >= 0; nIndex--) {
            int nCount = 0;
            string strRtnTmp = strMin.Substring(0, nIndex + 1);
            for (int nIndexSec = 0; nIndexSec < strs.Count &&
                    strs[nIndexSec].Contains(strRtnTmp); nIndexSec++)
                nCount++;
            if (nCount == strs.Count) {
                strRtn = strRtnTmp;
                break;
            }
        }
        return strRtn;
    }
}

全部评论

相关推荐

06-26 17:24
已编辑
宁波大学 Java
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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