Created
March 17, 2021 08:14
-
-
Save Peter-cloud-web/689ead6c947e24c6a2090e520014c119 to your computer and use it in GitHub Desktop.
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 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