Created
June 28, 2023 10:11
-
-
Save prianichnikov/a9e82f5cdd805920f5787aafaa46c3e3 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
/* | |
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