522. 最長特殊序列 II#
給定字符串列表 strs ,返回其中 最長的特殊序列 的長度。如果最長特殊序列不存在,返回 -1 。
特殊序列 定義如下:該序列為某字符串 獨有的子序列(即不能是其他字符串的子序列)。
s 的 子序列可以通過刪去字符串 s 中的某些字符實現。
-
例如,
"abc"是"aebdc"的子序列,因為您可以刪除"aebdc"中的下劃線字符來得到"abc"。"aebdc"的子序列還包括"aebdc"、"aeb"和""(空字符串)。
示例 1:
輸入: strs = ["aba","cdc","eae"]
輸出: 3
示例 2:
輸入: strs = ["aaa","aaa","aa"]
輸出: -1
提示:
2 <= strs.length <= 501 <= strs[i].length <= 10strs[i]只包含小寫英文字母
枚舉#
假如 strs = [ "abc", "abcd", "abcde" ],"abcd" 不是 "abc" 的子序列,但 "abcd" 是 abcde 的子序列,"abcde" 不是 "abcd"的子序列,也不是 abc 的子序列,所以我們要找的最長特殊序列即為 "abcde"。
代碼實現:
class Solution {
public:
int findLUSlength(vector<string>& strs) {
// str1 是否為 str2 的子序列
auto isSub = [&](const string &str1, const string &str2) -> bool {
int j = 0;
for (int i = 0; i < str2.size(); ++i) {
if (str1[j] == str2[i]) {
++j;
}
}
return j == str1.size();
};
int res = -1;
for (int i = 0; i < strs.size(); ++i) {
bool flag = true;
// 當遍歷的字符串的長度大於最長特殊序列長度時最長特殊序列長度才有增加的可能
if (strs[i].size() > res) {
for (int j = 0; j < strs.size(); ++j) {
if (j != i && isSub(strs[i], strs[j])) {
flag = false;
break;
}
}
if (flag) {
res = strs[i].size();
}
}
}
return res;
}
};
這道題其實不難,但是很容易錯,上面的代碼其實是存在 bug。
bug 就在判斷對當前遍歷的長度的判斷是否大於最長特殊序列的長度上 if (strs[i].size() > res),size() 返回類型為 size_t,是一個無符號類型,而 res 是一個有符號類型,在比較時 res 進行了整形提升,res 從有符號類型隱式轉換為無符號類型,res 在 64 位操作系統上 res 的值變為 。除了該位置的隱式轉換,還有多處隱式轉換問題。