您的位置:首页 > 编程语言 > Java开发

【小熊刷题】Longest Common Prefix <Leetcode 14, Java>

2015-09-11 09:53 741 查看

Question

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

*Difficulty: Easy

https://leetcode.com/problems/longest-common-prefix/

My Solution

找最短str,然后一个个字母比

public class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder sb = new StringBuilder();
if(strs.length == 0) return "";
if(strs.length == 1) return strs[0];
int minLen = Integer.MAX_VALUE;;
for(int i = 0; i < strs.length; i++){
minLen = Math.min(strs[i].length(), minLen);
}
boolean stop = false;
for(int i = 0; i < minLen; i++){
char c = strs[0].charAt(i);
for(String s : strs){
if(s.charAt(i) != c) {
stop=true;
break;
}
}
if(stop) break;
else sb.append(""+c);
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: