Skip to content

Commit 23d19ff

Browse files
committedMar 5, 2025
Add solution #522
1 parent b59cd8a commit 23d19ff

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,7 @@
418418
519|[Random Flip Matrix](./0519-random-flip-matrix.js)|Medium|
419419
520|[Detect Capital](./0520-detect-capital.js)|Easy|
420420
521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy|
421+
522|[Longest Uncommon Subsequence II](./0522-longest-uncommon-subsequence-ii.js)|Medium|
421422
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
422423
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
423424
542|[01 Matrix](./0542-01-matrix.js)|Medium|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 522. Longest Uncommon Subsequence II
3+
* https://leetcode.com/problems/longest-uncommon-subsequence-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of strings strs, return the length of the longest uncommon subsequence
7+
* between them. If the longest uncommon subsequence does not exist, return -1.
8+
*
9+
* An uncommon subsequence between an array of strings is a string that is a subsequence
10+
* of one string but not the others.
11+
*
12+
* A subsequence of a string s is a string that can be obtained after deleting any number
13+
* of characters from s.
14+
*
15+
* For example, "abc" is a subsequence of "aebdc" because you can delete the underlined
16+
* characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc",
17+
* "aeb", and "" (empty string).
18+
*/
19+
20+
/**
21+
* @param {string[]} strs
22+
* @return {number}
23+
*/
24+
var findLUSlength = function(strs) {
25+
strs.sort((a, b) => b.length - a.length);
26+
27+
for (let i = 0; i < strs.length; i++) {
28+
let isUnique = true;
29+
for (let j = 0; j < strs.length; j++) {
30+
if (i !== j && isSubsequence(strs[i], strs[j])) {
31+
isUnique = false;
32+
break;
33+
}
34+
}
35+
if (isUnique) {
36+
return strs[i].length;
37+
}
38+
}
39+
40+
return -1;
41+
42+
function isSubsequence(s1, s2) {
43+
let index = 0;
44+
for (const char of s2) {
45+
if (char === s1[index]) index++;
46+
if (index === s1.length) return true;
47+
}
48+
return false;
49+
}
50+
};

0 commit comments

Comments
 (0)
Please sign in to comment.