码迷,mamicode.com
首页 > 其他好文 > 详细

leet_14 Longest Common Prefix

时间:2016-01-26 12:19:17      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/kniught-ice/p/5159583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!