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 "".
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
consists of only lowercase English letters.
prefix = 단어 맨 처음에 오는 고정 문자열
중간에 오는 것은 체크되지 않는다
//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/
class Solution {
public String longestCommonPrefix(String[] strs) {
Integer size = Integer.MAX_VALUE;
String temp = "";
for (String str : strs) {
if (size > str.length()) {
size = str.length();
temp = str;
}
}
String prefix = "";
int isChecked = 0;
String minPrefix = "";
for (int i = 0; i < size; i++) {
isChecked = 0;
prefix += Character.toString(temp.charAt(i));
for (String str : strs) {
if (str.indexOf(prefix) == 0) {
isChecked++;
if (isChecked == strs.length)
minPrefix = prefix;
} else
break;
}
}
return minPrefix;
}
//https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/
class Solution {
public String longestCommonPrefix(String[] strs) {
String str = strs[0];
if (strs.length == 1) {
return str;
}
for (int i = 0; i < str.length(); i++) {
if (!check(strs, str.charAt(i), i))
return str.substring(0, i);
}
return str;
}
private boolean check(String[] strs, char c, int index) {
for (String str : strs) {
if (str.length() <= index)
return false;
if (c != str.charAt(index))
return false;
}
return true;
}
}
Exampel3 = {"dog", "racedog", "car"}