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.
思路一:採用java就是所有字符串一個個字符找過去,知道遇到不同的就輸出
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 1)
return strs[0];
StringBuilder sb = new StringBuilder();
if(strs.length > 1)
{
int len = strs[0].length();
for(int i = 0; i < len; i++)
{
char currch = strs[0].charAt(i);
for(int j = 1; j < strs.length; j++)
{
if(strs[j].length()<=i ||strs[j].charAt(i) != currch)
return sb.toString();
//當每個位置的值都相等,且來到最後一組了
if(strs[j].charAt(i) == currch && j == strs.length - 1)
{
sb.append(currch);
}
}
}
}
return sb.toString();
}
思路二:採用indexOf()和subString,從第二個串開始找與第一個串的公共子串,然後跟第三個串也是同樣。就是空間複雜度有點高:
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0)
return "";
String tmp = strs[0];
for(int i = 1; i < strs.length; i++){
//先跟第二個串匹配,找到相同的子串,每次沒找到公共子串,則
//原始串則減1,就是最後一個,直到是公共串,然後匹配下一個子串
while(strs[i].indexOf(tmp) != 0){
tmp = tmp.substring(0, tmp.length()-1);
}
}
return tmp;
}
}