2022年3月15日 星期二

LeetCode 14. Longest Common Prefix

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: 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 lower-case English letters.

解答:
使用 JAVA 語言
一開始想用字串來解此題,第一個一直 substring 減少 去和 第二個比對
後來發現,假如第一個字很長,第二個字比較短就會有問題

後來改成用單獨字去比對,再用for迴圈 + 遞迴比較穩定一點,不會有少字的問題

class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs.length == 1) return strs[0];

StringBuffer temp = new StringBuffer();

char[] a = strs[0].toCharArray();
int firstLength = a.length;

char[] a2 = strs[1].toCharArray();
int firstLength2 = a2.length;

if (firstLength>0 && firstLength2>0){
for (int i=0; i<firstLength && i<firstLength2; i++){
if (a[i] != a2[i]){
break;
} else {
temp.append(a[i]);
}
}
}

String[] newStrs = new String[strs.length-1];

for (int i=0; i<strs.length-1; i++){
if (i==0)
newStrs[0] = temp.toString();
else
newStrs[i] = strs[i+1];
}
return longestCommonPrefix(newStrs);
}
}

沒有留言:

張貼留言

Android Studio IDE 錯誤

 :app:compile xxxxx JavaWithJavac FAILED An exception has occurred in the compiler (1.8.0_312). Please file a bug against the Java compiler ...