一、题目要求
给定义一个字符串列表strs,找出字符串数组中最长特殊序列并返回该长度。特殊序列的定义如下:该序列不能是其他字符串的子序列。
如果source字符串是target字符串的子序列,那么target字符串中删除某些字符后可以得到source字符串。
例如,“abc” 是 “exabxc” 的子序列, 因为可以通过删除‘e’、‘x’和‘x’得到字符串“abc”
二、解题思路
示例 1:
输入:strs = ["aba","cdc","eae"]
输出:3
1.判断是最长特殊序列
通过对strs的遍历,
1.判断strs[0]是不是strs中的特殊序列,如果是计算长度;
2.判断strs[1]是不是strs中的特殊序列,如果是计算长度;
3.判断strs[2]是不是strs中的特殊序列,如果是计算长度;
最后返回最大长度
2.判断是否为子序列
使用双指针,判断source是target的子序列
1、首先判断source和target的字符长度,如果source长度大于target长度则直接返回false。
2、遍历source和target,首先定义index1和index2,记录访问的source和target的位置。
如果source.charAt(index1)!=target.charAt(index2),则index2执行加1操作;
如果source.charAt(index1)==target.charAt(index2),则index1执行加1操作,index2也执行加1操作。
3、如果index1遍历完成则返回true,否则返回false。
三、代码实现
class Solution {
public int findLUSlength(String[] strs) {
int length = strs.length;
int max = -1;
for (int i = 0; i < length; i++) {
boolean bool = true;
for (int j = 0; j < length; j++) {
if (i == j) {
continue;
}
// 如果是子序列则直接跳出
if (isSubSequence(strs[i], strs[j])) {
bool = false;
break;
}
}
if (bool) {
max = Math.max(max, strs[i].length());
}
}
return max;
}
private boolean isSubSequence(String s, String d) {
if (s.length() > d.length()) {
return false;
}
int sIndex = 0;
int dIndex = 0;
while (sIndex < s.length() && dIndex < d.length()) {
if (s.charAt(sIndex) == d.charAt(dIndex)) {
sIndex++;
}
dIndex++;
if (sIndex < s.length() && dIndex >= d.length()) {
return false;
}
}
return true;
}
}