天天看點

14 最長公共字首 Java

leetcode14 最長公共字首

題目描述

編寫一個函數來查找字元串數組中的最長公共字首。

如果不存在公共字首,傳回空字元串

""

算法思路

此處我采用縱向搜尋的方法,對字元串數組的每一列進行比較,直到比較長度到達某個最短字元串或者遇到不相同字元。

代碼實作

public class Solution {
    public static void main(String args[]){
        String[] strs =  {"qwerewqr", "qwertydafdf","qwertyuiop"};

        System.out.println(longestCommonPrefix(strs));

    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        int length = strs[0].length();  //第一個字元長度
        int count = strs.length;        //字元串個數
        for (int i = 0; i < length; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < count; j++) {
                //如果目前周遊到的字元位置為該字元串的長度或者字元不相同,傳回前面的字元串
                if (i == strs[j].length() || strs[j].charAt(i) != c) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];     //說明第一個字元串即為最長字首
    }
}