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

LeetCode #14 Longest Common Prefix (E)

时间:2015-10-10 00:11:15      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

[Problem]

Write a function to find the longest common prefix string amongst an array of strings.

 

[Analysis]

思路非常简单,循环验证每一个字符串就可以通过OJ,代码也没有优化。

 

[Solution]

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        
        if (strs.length == 1) {
            return strs[0];
        } 
        
        int idx = 0;
        boolean flag = true;
        while (idx < strs[0].length()) {
            char c = strs[0].charAt(idx);
            for (int i = 1; i < strs.length; i++) {
                if (idx >= strs[i].length() || strs[i].charAt(idx) != c) {
                    flag = false;
                    break;
                }
            }
            
            if (flag) {
                idx++;
            } else {
                break;
            }
        }
        
        return strs[0].substring(0, idx);
    }
}

 

LeetCode #14 Longest Common Prefix (E)

标签:

原文地址:http://www.cnblogs.com/zhangqieyi/p/4865394.html

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