leetcode014 Longest Common Prefix

3058 ワード

タイトル
14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array of strings.
考え方:
私の考えはjavaの不規則な2次元配列を利用して、与えられた文字列配列を格納することです.2次元配列の各行為の元の文字列配列の1つの文字列は、以下のようにします.
//String  :
["hello","hell","hi","helloword"] 
//          :
h e l l o
h e l l
h i
h e l l o w o r l d
  • この2次元配列を構築する際には、空の状況をチェックし、最短文字長を記録することに注意してください.
  • は、その後、ある文字が他の文字と等しくないまで、この2次元配列を列ごとに巡回し、文字列を構築して返します.
  • 遍歴中に返されなかった場合、すなわちプログラムが最後まで実行された場合、与えられた文字列のうち1つが完全な同じ接頭辞であることを示し、2次元配列の中で1行の構造文字列を勝手に探すだけで、もちろん最初の行の最方便を探して、0から、覚え始めた最短の長さを長さnew列とする.PS:最初は、指定された文字列配列が空であるか、そのうちの1つが空であるかなどの特殊な状況を排除します.

  • コード:
    public String longestCommonPrefix(String[] strs)
    {
        if(strs.length == 0)
            return "";
        int shortestLength = Integer.MAX_VALUE;
    
        //         
        char[][] chars = new char[strs.length][];
        for(int i = 0; i < chars.length; i++)
        {
            if(strs[i] == null || strs[i].length() == 0)
                return "";
            chars[i] = strs[i].toCharArray();
            if(shortestLength > chars[i].length)
                shortestLength = chars[i].length;
        }
    
        //    ,     
        //         
        int i, j;
        for(j = 0; j < shortestLength; j++)
        {
            int tmp_char = chars[0][j];
            for(i = 1; i < chars.length; i++)
            {
                if(tmp_char != chars[i][j])
                    return new String(chars[0],0,j);
            }
        }
        return new String(chars[0],0,shortestLength);
    }

    結果の詳細(図):