天天看點

函數查找字元串數組中最長公共字首

最長公共字首 編寫一個函數來查找字元串數組中的最長公共字首 如果不存在公共字首 傳回空我字元串 " "

進行一個 字元的比對 ;傳回核對字首的字元串。

函數查找字元串數組中最長公共字首
package LeeCodeTest14;


/**
 * 最長公共字首
 * 編寫一個公共函數 來查找字元串數組中的最長公共字首
 * 如果不存在公共字首 傳回空字元串 " "。
 */
public class LeeCodeTest14 {
    public String longestCommonPrefix(String[] Str){
        //查找公共字首 查找數組中的字元串中的公共字首
        //首先我們的前提是尋找出字元串的公共字首
        //我們不斷進行測試怎麼測試呢 我們将數組中的第一個字元串作為一個标本;
        //将第一個字元串不斷的和數組中的元素進行循環周遊比較直到 我們的公共字元串找到就傳回
        String s =Str[0];
        for (String string :Str
             ) {
            while (!string.startsWith(s)){
                if(s.length()==0)
                    return "";
                //公共字首不比對的時候我們将數組中的第一個字元串進行縮小直到找到那個公共字元串 縮小的方法使用的是 subString進行對字元串的剪切
                s=s.substring(0,s.length()-1);
            }
        }
        return s;
    }
    public static void main(String[] args) {
        LeeCodeTest14 test = new LeeCodeTest14();
        String[] Str= new String[]{"flower","flow","flight","fl","fli"};
        String s = test.longestCommonPrefix(Str);
        System.out.println(s);
    }
}