int n = strs.size(); int ans = -1; for (int i = 0; i < n; ++i) { bool check = true; for (int j = 0; j < n; ++j) { if (i != j && is_subseq(strs[i], strs[j])) { check = false; break; } } if (check) { ans = max(ans, static_cast<int>(strs[i].size())); } } return ans; } };
classSolution: deffindLUSlength(self, strs: List[str]) -> int: defis_subseq(s: str, t: str) -> bool: pt_s = pt_t = 0 while pt_s < len(s) and pt_t < len(t): if s[pt_s] == t[pt_t]: pt_s += 1 pt_t += 1 return pt_s == len(s) ans = -1 for i, s inenumerate(strs): check = True for j, t inenumerate(strs): if i != j and is_subseq(s, t): check = False break if check: ans = max(ans, len(s)) return ans
funcisSubseq(s, t string)bool { ptS := 0 for ptT := range t { if s[ptS] == t[ptT] { if ptS++; ptS == len(s) { returntrue } } } returnfalse }
funcfindLUSlength(strs []string)int { ans := -1 next: for i, s := range strs { for j, t := range strs { if i != j && isSubseq(s, t) { continue next } } iflen(s) > ans { ans = len(s) } } return ans }
var findLUSlength = function(strs) { const n = strs.length; let ans = -1; for (let i = 0; i < n; ++i) { let check = true; for (let j = 0; j < n; ++j) { if (i !== j && isSubseq(strs[i], strs[j])) { check = false; break; } } if (check) { ans = Math.max(ans, strs[i].length); } } return ans; };
constisSubseq = (s, t) => { let ptS = 0, ptT = 0; while (ptS < s.length && ptT < t.length) { if (s[ptS] === t[ptT]) { ++ptS; } ++ptT; } return ptS === s.length; }
复杂度分析
时间复杂度:O(n^2 \cdot l),其中 n 是数组 strs 的长度,l 是字符串的平均长度。