Created
December 20, 2014 07:29
-
-
Save wangchauyan/45ccb42de54cbb3bcf15 to your computer and use it in GitHub Desktop.
Find out longest common prefix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package wcy.leetcode.gist; | |
/** | |
* Created by ChauyanWang on 12/20/14. | |
*/ | |
public class Longest_Common_Prefix { | |
int findMinLength(String[] strs) { | |
int minLength = Integer.MAX_VALUE; | |
for(String str : strs) { | |
if(str.length() < minLength) minLength = str.length(); | |
} | |
return minLength; | |
} | |
public String Solution (String[] strs) { | |
StringBuffer result = new StringBuffer(); | |
if(strs == null || strs.length == 0) return result.toString(); | |
final int minLength = findMinLength(strs); | |
for(int i = 0; i < minLength; i++) { | |
for(int j = 1 ; j < strs.length; j++) | |
if(strs[j].charAt(i) != strs[0].charAt(i)) return result.toString(); | |
result.append(strs[0].charAt(i)); | |
} | |
return result.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment