Created
May 20, 2013 17:22
-
-
Save daifu/5613718 to your computer and use it in GitHub Desktop.
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
| /* | |
| Write a function to find the longest common prefix string amongst an array of strings. | |
| Algorithm: | |
| 1. Traverse through all the str inside strs and keep track of the longest | |
| common prefix. | |
| 2. Make sure the lenght of the string does not exceed the length of str. | |
| */ | |
| public class Solution { | |
| public String longestCommonPrefix(String[] strs) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if(strs.length == 0) return ""; | |
| StringBuffer sb = new StringBuffer(); | |
| int start = 0; | |
| while(true) { | |
| if(start == strs[0].length()) return sb.toString(); | |
| char cur = strs[0].charAt(start); | |
| for(int i = 1; i < strs.length; i++) { | |
| if(start == strs[i].length()) return sb.toString(); | |
| if(cur != strs[i].charAt(start)) return sb.toString(); | |
| } | |
| sb.append(cur); | |
| start++; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment