這題是要找出陣列中字串最小相同的的字元。如果無則會返回空字串""。
LeetCode 題目連結
https://leetcode.com/problems/longest-common-prefix/
題目
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: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
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: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters
a-z.Accept 作法
我發現自己太急想知道答案會太快送出,之後要考慮多測試幾個案例再送出,不然總是會遺漏。
Runtime: 17 ms
Memory: 41.4 MB
Java
Runtime: 17 ms
Memory: 41.4 MB
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
if(strs.length == 1 || strs[0].length() == 0)
return strs[0];
String firstStr = strs[0];
String finalResult = null;
for(int i = 1; i < strs.length; i++){
String result = "";
for(int j = 0; j < strs[i].length();j++){
if(firstStr.length() <= j || firstStr.charAt(j) != strs[i].charAt(j)){
break;
}
result = result+ strs[i].charAt(j);
}
if(finalResult == null || finalResult.length() > result.length()){
finalResult = result;
}
}
return finalResult;
}
}
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。

沒有留言:
張貼留言