Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
一个个比就行了,找到最长的匹配子串。
1 public class Solution { 2 public String longestCommonPrefix(String[] strs) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 if(strs == null || strs.length == 0 || strs[0] == null || strs[0].length() == 0) return ""; 5 for(int i = 0; i < strs[0].length(); i ++){ 6 char c = strs[0].charAt(i); 7 for(int j = 0; j < strs.length; j ++){ 8 if(!(strs[j].length() > i && strs[j].charAt(i) == c)){ 9 return strs[0].substring(0, i); 10 } 11 } 12 } 13 return strs[0]; 14 } 15 }
posted on 2013-10-17 12:27 Step-BY-Step 阅读(149) 评论(0) 编辑 收藏 举报