题解 | #最长公共前缀#

最长公共前缀

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;
    }
}

全部评论

相关推荐

找到实习就改名4月17日下午更改:1600一个月?
点赞 评论 收藏
分享
抱抱碍事梨a:三点建议,第一点是建议再做一个项目,把自我介绍部分顶了,第二点是中南大学加黑加粗,第三点是建议加v详细交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务