1. 題目
1.1 英文題目
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 "".
1.2 中文題目
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 ""。
1.3輸入輸出
輸入 | 輸出 |
---|---|
strs = ["flower","flow","flight"] | "fl" |
strs = ["dog","racecar","car"] | "" |
1.4 約束條件
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lower-case English letters.
2. 分析
2.1 一般方法
看到這道題,最簡單的方法就是兩層for迴圈,最外層是對第一個字串進行遍歷(其實第幾個字串都無所謂),內層是對字元陣列進行遍歷,意思也就是先看所有字串第一個元素是否都一樣,再看第二個,第三個,以此類推,當遇到有不同的時候,就可以跳出外層迴圈。程式碼如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
for (unsigned int i = 0; i < strs[0].size(); i++)
{
unsigned int count = 0;
for (unsigned int j = 0; j < strs.size(); j++)
{
char temp = strs[0][i];
if (i != strs[j].size() && strs[j][i] == temp)//
count++;
else
goto here;
if (count == strs.size())
ans += strs[0][i];
}
}
here:
return ans;
}
};
2.2 改進演算法(賊好使)
上述演算法使用goto跳出兩層迴圈,而goto的使用很多人是不太推薦使用的,同時聯想到for迴圈的第二項就是一個判斷語句,因此可以將goto判斷語句改到for迴圈裡,具體程式碼如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string ans;
for (unsigned int i = 0; i < strs[0].size(); i++)
{
unsigned int count = 1;
unsigned int j = 1;
int temp = strs[0][i];
for (; j < strs.size() && i != strs[j].size() && strs[j][i] == temp; j++)
count++;
if (count == strs.size())
ans += strs[0][i];
else
break;
}
return ans;
}
};
這個演算法時間消耗0ms,空間消耗9M,非常不錯!