leet_14 Longest Common Prefix

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]14_Longest Common Prefix

14. Longest Common Prefix

14. Longest Common Prefix

#Leetcode# 14. Longest Common Prefix

leetcode14. longest common prefix

14. Longest Common Prefix