Skip to content

Instantly share code, notes, and snippets.

@sogwiz
Created June 24, 2019 19:18
Show Gist options
  • Save sogwiz/ee3f3cfb30e1d114d466f7179f81c1c7 to your computer and use it in GitHub Desktop.
Save sogwiz/ee3f3cfb30e1d114d466f7179f81c1c7 to your computer and use it in GitHub Desktop.
Longestcommonprefix
/**
* 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