【LeetCode】ヒドイラード14最長公開プレフィックス(Longest Comon Profix)


【LeetCode】ヒドイラード14最長公開プレフィックス(Longest Comon Profix)
テーマの説明
文字列配列の最長共通プレフィックスを検索する関数を作成します。共通のプレフィックスが存在しない場合は、空の文字列「」を返します。

例1:
入力:[[flower],[flow],[flight]出力:[flight]
例2:
入力:["dog"は、"racecar"は、"car"出力:"は、入力に共通プレフィックスが存在しないと解釈します。
Description
Write a function to find the longest common prefix string amongst an array of strigs.If there isのcommon prefix,return an empty string".
Example
Example 1:
Input:[[flower],[flow],[flight]Output:"fl"
Example 2:
Input:[dog],“racecar”,“car”Output:“Explanion:The re isのcommon prefix among the input strigs.
法を解く
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0)
            return "";
        StringBuilder sb = new StringBuilder();
        int i=0;
        while(true){
            if(i==strs[0].length())
                return sb.toString();
            char ch = strs[0].charAt(i);
            for(String str : strs){
                if(i==str.length() || ch != str.charAt(i))
                    return sb.toString();
            }
            sb.append(ch);
            i++;
        }
    }
}