Skip to content

Instantly share code, notes, and snippets.

@prianichnikov
Created June 28, 2023 10:11
Show Gist options
  • Save prianichnikov/a9e82f5cdd805920f5787aafaa46c3e3 to your computer and use it in GitHub Desktop.
Save prianichnikov/a9e82f5cdd805920f5787aafaa46c3e3 to your computer and use it in GitHub Desktop.
/*
Longest Common Prefix
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
*/
public class Algo_LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
StringBuilder result = new StringBuilder();
String firstString = strs[0];
int charIndex = 0;
for (char currentChar : firstString.toCharArray()) {
for (int stringIndex = 1; stringIndex < strs.length; stringIndex++) {
char c1 = strs[stringIndex].charAt(charIndex);
if (c1 != currentChar) {
return result.toString();
}
}
result.append(currentChar);
charIndex++;
}
return result.toString();
}
public static void main(String[] args) {
String[] strs = {"flower","flow","flight"};
String[] strs2 = {"dog","racecar","car"};
Solution s1 = new Solution();
System.out.println(s1.longestCommonPrefix(strs));
System.out.println(s1.longestCommonPrefix(strs2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment