LeetCode 521 最长特殊序列I
题目
方法:脑筋急转弯
字符串的子序列的长度不会超过该字符串的长度。若子序列的长度等于字符串的长度,那么子序列就是该字符串。
-
若两字符串相同(长度相同且内容相同),那么任一字符串的子序列均会出现在两个字符串中,此时应返回
-1
-
若两字符串不相同
- 当两字符串长度不同时,可以选择较长的字符串作为最长特殊序列,显然它不会是较短的字符串的子序列
- 当两字符串长度相同时(但不是同一字符串),仍然可以选择其中的一个字符串作为最长特殊序列,它不会是另一个字符串的子序列
class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
}
return Math.max(a.length(), b.length());
}
}
-
时间复杂度: O ( n ) O(n) O(n)
-
空间复杂度: O ( 1 ) O(1) O(1)
String
类的equals
方法:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
LeetCode 522 最长特殊序列II
题目
方法一:暴力
生成所有字符串的所有子序列,将其存储在 HashMap
中,并记录每个子序列出现的次数。然后找出出现次数为 1
的最长子序列。如果不存在这样的子序列,返回−1
。
class Solution {
public int findLUSlength(String[] strs) {
HashMap< String, Integer > map = new HashMap < > ();
for (String s: strs) {
for (int i = 0; i < (1 << s.length()); i++) {
String t = "";
for (int j = 0; j < s.length(); j++) {
// System.out.println("i = " + i + " j = " + j + " (i >> j) = " + (i >> j) + " ((i >> j) & 1) = " + ((i >> j) & 1));
if (((i >> j) & 1) != 0) {
t += s.charAt(j);
}
}
map.put(t, map.getOrDefault(t, 0) +1);
}
}
int res = -1;
for (String s: map.keySet()) {
if (map.get(s) == 1) {
res = Math.max(res, s.length());
}
}
return res;
}
}
- 时间复杂度: O ( n × 2 x ) O(n \times 2^x) O(n×2x),其中 x x x是所有字符串的平均长度, n n n是字符串的数量
- 空间复杂度: O ( n × 2 x ) O(n \times 2^x) O(n×2x)
方法二:检查每个字符串
如果存在这样的特殊序列,那么它一定是某个给定的字符串。
检查每个字符串是否是其他字符串的子序列:
- 如果不是,则它是一个特殊序列。最后返回长度最大的特殊序列。
- 如果不存在特殊序列,返回
-1
。
class Solution {
// 判断x是否是y的子序列
// s 的子序列可以通过删去字符串 s 中的某些字符实现
public boolean isSubsequence(String x, String y) {
int j = 0;
for (int i = 0; i < y.length() && j < x.length(); i++) {
if (x.charAt(j) == y.charAt(i)) {
j++;
}
}
return j == x.length();
}
public int findLUSlength(String[] strs) {
int res = -1;
for (int i = 0; i < strs.length; i++) {
int j = 0;
for (j = 0; j < strs.length; j++) {
if (j == i) {
continue ;
}
if (isSubsequence(strs[i], strs[j])) {
break;
}
}
if (j == strs.length) {
res = Math.max(res, strs[i].length());
}
}
return res;
}
}
- 时间复杂度: O ( x × n 2 ) O(x \times n^2) O(x×n2),其中 n n n是字符串的数量, x x x是每个字符串的平均长度
- 空间复杂度: O ( 1 ) O(1) O(1)