Created
February 25, 2013 18:53
-
-
Save daifu/5032239 to your computer and use it in GitHub Desktop.
Write a function to find the longest common prefix string amongst an array of strings.
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
| public class Solution { | |
| public String longestCommonPrefix(String[] strs) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| int size = strs.length; | |
| if(size == 0) { | |
| return ""; | |
| } | |
| String common = strs[0]; | |
| for (int i = 1; i < size; i++){ | |
| String ahead = strs[i]; | |
| common = longestCommonPrefixHelper(common, ahead); | |
| } | |
| return common; | |
| } | |
| public String longestCommonPrefixHelper(String common, String next) { | |
| int size = (common.length() >= next.length()) ? next.length() : common.length(); | |
| StringBuffer sb = new StringBuffer(); | |
| for(int i = 0; i < size; i++) { | |
| if(common.charAt(i) == next.charAt(i)) { | |
| sb.append(common.charAt(i)); | |
| } else { | |
| i = size; | |
| } | |
| } | |
| return sb.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment