Created
June 24, 2019 19:18
-
-
Save sogwiz/ee3f3cfb30e1d114d466f7179f81c1c7 to your computer and use it in GitHub Desktop.
Longestcommonprefix
This file contains 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
/** | |
* Created by sargonbenjamin on 6/21/19. | |
* https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/ | |
*/ | |
public class LongestCommonPrefix { | |
public String longestCommonPrefix(String[] strs) { | |
if(strs==null || strs.length == 0 || strs[0].length()==0)return ""; | |
StringBuilder prefix = new StringBuilder(""); | |
for(int charIdx = 0; charIdx<strs[0].length(); charIdx++){ | |
char currLetter = strs[0].charAt(charIdx); | |
for(int j = 0; j < strs.length; j++){ | |
if(strs[j].length() <= charIdx || currLetter != strs[j].charAt(charIdx)){ | |
return prefix.toString(); | |
} | |
} | |
prefix.append(currLetter); | |
} | |
return prefix.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment