Skip to content

Instantly share code, notes, and snippets.

@wangchauyan
Created December 20, 2014 07:29
Show Gist options
  • Save wangchauyan/45ccb42de54cbb3bcf15 to your computer and use it in GitHub Desktop.
Save wangchauyan/45ccb42de54cbb3bcf15 to your computer and use it in GitHub Desktop.
Find out longest common prefix
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