Created
May 6, 2020 13:41
-
-
Save AnjaliManhas/0dfa13fdc7bc89937bae0e65a93306dd to your computer and use it in GitHub Desktop.
Longest Common Prefix Leetcode- Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
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
public class Solution { | |
public String longestCommonPrefix(String[] strs) { | |
if(strs.length==0||strs==null) return ""; | |
String prefix = strs[0]; | |
for(int i = 1;i<strs.length;i++){ | |
if(strs[i] == prefix) continue; | |
int k = 0; | |
while(k<prefix.length()&&k<strs[i].length()&&prefix.charAt(k)==strs[i].charAt(k)){ | |
k++; | |
} | |
prefix = prefix.substring(0,k); | |
} | |
return prefix; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment