leet_14 Longest Common Prefix

package com.mingxin.leetcode.leet_14;

/**
 * Created by Administrator on 2016/1/25.
 */
public class LongestCommonPrefix {

    public static void main(String[] args){

        String[] strs = {"adfdgdf", "adferef", "adfeergf", "adf"};
        String[] strs1 = {"a", "b"};
        String result = longestCommonPrefix(strs1);
        System.out.println(result);
    }

    public static String longestCommonPrefix(String[] strs) {

        if(null == strs){
            return "";
        }
        int strLength = strs.length;
        if(strLength == 0){
            return "";
        }

        int minLength = strs[0].length();

        for(String str:strs){
            int length = str.length();
            if(length < minLength){
                minLength = length;
            }
        }

        if(minLength == 0){
            return "";
        }
        //不要用char[]会有坑
        StringBuilder sb = new StringBuilder();
        int endFlag = 0;//解决break跳不出第二重循环的问题
        for(int i = 0; i < minLength; i++){

            if(endFlag == 1){
                break;
            }

            char c = strs[0].charAt(i);
            for(int j = 0; j < strLength; j++){
                if (c != strs[j].charAt(i)) {
                    endFlag = 1;
                    break;
                }
                if(j == strLength-1){
                    sb.append(c);
                }
            }
        }

        return sb.toString();
    }
}

 

你可能感兴趣的:(leet_14 Longest Common Prefix)