天天看點

最長公共字首(string[] c#)

編寫一個函數來查找字元串數組中的最長公共字首。

如果不存在公共字首,傳回空字元串 ""。

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"
示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
說明:

所有輸入隻包含小寫字母 a-z 。

題目來源:LeetCode
           

思路:縱向掃描

縱向掃描時,從前往後周遊所有字元串的每一列,比較相同列上的字元是否相同,如果相同則繼續對下一列進行比較,如果不相同則目前列不再屬于公共字首,目前列之前的部分為最長公共字首。

public string LongestCommonPrefix(string[] strs)
        {
            if (strs.Length == 0)
            {
                return "";
            }
            if (strs.Length == 1)
            {
                return strs[0];
            }
            string Prefix = strs[0];
            int length = strs[0].Length;
            for (int i = 0; i < length; i++)
            {
                for (int j = 1; j < strs.Length; j++)
                {
                    if (strs[j].Length == i || strs[0][i] != strs[j][i]  )
                    {
                        return strs[0].Substring(0, i);
                    }
                }
            }

            return Prefix;
        }
}