14. Longest Common Prefix - Easy
前往題目
想法
- 找到最長的那個,全部記錄下來,用hashmap,或是26空位的陣列
- 接著檢查其餘所有的
String
,每次都紀錄最小值,也就是如果第一個可以匹配到4個,第二個只能2個,那結果還是2 - 但是這樣有個問題,因為每個都是從0個開始算,那完全沒有的話就變成0是答案了…
廢棄Code
class Solution {
public String longestCommonPrefix(String[] strs) {
int[] charCount = new int[26];
Arrays.fill(charList, 0);
int longestIndex = 0;
// Find the longest string
for (int i = 1; i < strs.length; ++i) {
if (strs[longestIndex].length() < str[i].length()){
longestIndex = i;
}
}
// Count the char
for (char c : strs[longestIndex]) {
charCount[c - 'a']++;
}
int res = Integer.MAX_VALUE;
int lengthOfTheLongestStr = strs[longestIndex].length();
// Every string
for (String s : strs) {
int count = 0;
int length = s.length();
// Check chars
for (int i = 0; i < length; ++i) {
if (strs[longestIndex].charAt(i) == s.charAt(i)) {
++count;
}
}
count = Math.min(count, )
}
}
}
思路
其實更簡單😂
- 直接拿第一個string來當基準
- 然後比較每一個string的第一個字,接著第二個,以此類推
- 遇到出界(比較短的字串)或是不匹配的字,直接回傳答案,因為最多一定就在那裡了,畢竟短的字串不可能變長
Code
class Solution {
public String longestCommonPrefix(String[] strs) {
StringBuilder res = new StringBuilder("");
// Use the first string to check
for (int i = 0; i < strs[0].length(); ++i) {
// Check every the ith item of every string
for (String s : strs) {
// Prevent out of bound and check common prefix
if (i == s.length() ||
strs[0].charAt(i) != s.charAt(i)) {
return res.toString();
}
}
res.append(strs[0].charAt(i));
}
return res.toString();
}
}
2024/05/02
- Accepted
14. Longest Common Prefix - Easy
https://f88083.github.io/2023/12/28/14-Longest-Common-Prefix-Easy/