2020年3月15日 星期日

[LeetCode] 14. Longest Common Prefix (Easy)



這題是要找出陣列中字串最小相同的的字元。如果無則會返回空字串""。



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.

Accept 作法

我發現自己太急想知道答案會太快送出,之後要考慮多測試幾個案例再送出,不然總是會遺漏。


Runtime: 17 ms
Memory: 41.4 MB

Java
  1. class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. if(strs.length == 0)
  4. return "";
  5. if(strs.length == 1 || strs[0].length() == 0)
  6. return strs[0];
  7. String firstStr = strs[0];
  8. String finalResult = null;
  9. for(int i = 1; i < strs.length; i++){
  10. String result = "";
  11. for(int j = 0; j < strs[i].length();j++){
  12. if(firstStr.length() <= j || firstStr.charAt(j) != strs[i].charAt(j)){
  13. break;
  14. }
  15. result = result+ strs[i].charAt(j);
  16. }
  17. if(finalResult == null || finalResult.length() > result.length()){
  18. finalResult = result;
  19. }
  20. }
  21. return finalResult;
  22. }
  23. }



更多 LeetCode 相關資源

 


複習程式面試書籍


除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備

需要的話可以看看,寫得很仔細。



書名:提升程式設計師的面試力:189道面試題目與解答




相關 LeetCode文章一律會放在 程式解題 標籤分類,歡迎持續追蹤。


沒有留言:

張貼留言