LeetCode 14.Longest Common Prefix , 最長公共前綴 ,C#

前言

本文介紹了 LeetCode 第 14 題 , "Longest Common Prefix ", 也就是 “最長公共前綴” 的問題.

本文使用 C# 語言完成題目,介紹了1種方法供大家參考。

題目

English

LeetCode 14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string “”.

Example 1:

Input: [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

中文

LeetCode 14. 最長公共前綴

編寫一個函數來查找字符串數組中的最長公共前綴。

如果不存在公共前綴,返回空字符串 “”。

示例 1:

輸入: [“flower”,“flow”,“flight”]
輸出: “fl”

示例 2:

輸入: [“dog”,“racecar”,“car”]
輸出: “”
解釋: 輸入不存在公共前綴。

解決方案

本文給出了1種解決方法。更多的解法可以參考官方題解。

想象一下,每個單詞佔一行,左對齊,一條豎直的紅色激光從左向右掃描,若掃描到一列的字母不全相同,則停止並輸出結果即可。

在這裏插入圖片描述

參考代碼:

    public string LongestCommonPrefix(string[] strs)
    {
        if (strs.Length == 0) return "";
        int p = 0;
        while (true)
        {
            if (strs[0].Length <= p) break;
            bool allSame = true;
            for (int i = 1; i < strs.Length; i++)
            {
                if ((strs[i].Length <= p) || (strs[i][p] != strs[0][p]))
                {
                    allSame = false;
                    break;
                }
            }
            if (allSame) p++;
            else break;
        }
        return strs[0].Substring(0, p);
    }

執行結果

執行結果 通過。 執行用時: 108ms, 內存消耗 24.6M

複雜度分析

時間複雜度:O(S)

S表示strs中所有字符數量之和。 更進一步,可以認爲是 O( len(strs) * min(len(item)) ),即字符串數量與最短字符串長度的乘積。

空間複雜度:O(1)

常數個變量。

參考資料彙總

題目:

https://leetcode-cn.com/problems/longest-common-prefix/

官方題解:

https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章