LeetCode: 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.

解法: 以陣列第一個元素當作prefix,把此prefix跟陣列所有元素比較,如果沒有則去除prefix字元再重複比較,直到所有元素皆比較完。

public class Solution {
    public string LongestCommonPrefix(string[] strs) {
        
        if (strs == null || strs.Length == 0)
            return "";

        string pre = strs[0];

        int i = 1;

        while(i < strs.Length)
        {
            while (strs[i].IndexOf(pre) != 0)
                pre = pre.Substring(0, pre.Length - 1);
            i++;
        }

        return pre;
    }  
}

Ref:

https://leetcode.com/articles/longest-common-prefix/