Skip to content

Instantly share code, notes, and snippets.

@AnjaliManhas
Created May 6, 2020 13:41
Show Gist options
  • Save AnjaliManhas/0dfa13fdc7bc89937bae0e65a93306dd to your computer and use it in GitHub Desktop.
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 "".
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