Skip to content

Instantly share code, notes, and snippets.

@Peter-cloud-web
Created March 17, 2021 08:14
Show Gist options
  • Select an option

  • Save Peter-cloud-web/689ead6c947e24c6a2090e520014c119 to your computer and use it in GitHub Desktop.

Select an option

Save Peter-cloud-web/689ead6c947e24c6a2090e520014c119 to your computer and use it in GitHub Desktop.
public class LongestCommonPrefix {
public static String longestCommonPrefix(String[] strs) throws ArrayIndexOutOfBoundsException {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < strs.length; i++){
char c = strs[0].charAt(i);
for( int j = 1; j < strs.length; j++){
if(strs[j].charAt(i) != c){
sb.append(strs[0].substring(0,i));
}
}
}
return sb.toString();
}
public static void main(String[] args){
String[] strs = {"Flower", "Flow","Floj","Flore"};
String lp = LongestCommonPrefix.longestCommonPrefix(strs);
System.out.println(lp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment