알고리즘 문제/Leetcode
Longest Common Prefix
BEstyle
2022. 9. 28. 20:04
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 "".
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.
Constraints:
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters.
class Solution {
public static String longestCommonPrefix(String[] strs) {
//Finding min length of string array.
int minLength=strs[0].length();
for (int i=0; i<strs.length; i++){
if (strs[i].length()<minLength){
minLength=strs[i].length();
}
}
System.out.println(minLength);
String commonPrefix="";
char checkLetter;
for(int j=0; j<minLength; j++){
checkLetter = strs[0].charAt(j);
for (int i=0; i<strs.length; i++){
if (strs[i].charAt(j)==checkLetter){
System.out.println(strs[i].charAt(j)==checkLetter);
}else{
System.out.println(commonPrefix);
return commonPrefix;
}
}
commonPrefix+=strs[0].charAt(j);
System.out.println(commonPrefix);
}
System.out.println(commonPrefix);
return commonPrefix;
}
}