6. 最长子序列
524. Longest Word in Dictionary through Deleting (Medium)
Input:
s = “abpcplea”, d = [“ale”,“apple”,“monkey”,“plea”]
Output:
“apple”
题目描述:删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。
通过删除字符串 s 中的一个字符能得到字符串 t,可以认为 t 是 s 的子序列,我们可以使用双指针来判断一个字符串是否为另一个字符串的子序列。
代码实现:含注释
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 7. 最长子序列
* 524. Longest Word in Dictionary through Deleting (Medium)
*
* Input:
* s = "abpcplea", d = ["ale","apple","monkey","plea"]
*
* Output:
* "apple"
*
* 题目描述:删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,
* 找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。
*
* 通过删除字符串 s 中的一个字符能得到字符串 t,可以认为 t 是 s 的子序列,
* 我们可以使用双指针来判断一个字符串是否为另一个字符串的子序列。
*/
public class DoublePointer6_findLongWord {
public static void main(String[] args) {
//创建一个引用,并初始化,而且关联对象
String str = new String("abpcplea");
//创建引用,初始化为空,不关联对象
String longString = "";
//采用Arrays.asList()方法进行链表的批量初始化赋值
List<String> candidates = new ArrayList<>(Arrays.asList("ale","apple","monkey","plea"));
//foreach 循环进行List的遍历
for (String target: candidates){
//剪枝操作,如果存在以下两种情况,则直接跳过,相当于剪枝
if (longString.length()>target.length() ||
(longString.length()==target.length() &&
longString.compareTo(target)<0)){
continue;
}
//调用isSubString()方法,判断是否为子串
if (isSubString(str,target)){
longString = target;
}
}
System.out.println(longString);
}
public static boolean isSubString(String str,String target){
//双指针进行子串的判断
int str_index = 0;
int target_index = 0;
while (str_index < str.length() && target_index < target.length()){
if(str.charAt(str_index) == target.charAt(target_index)){
target_index++;
}
str_index++;
/**
* if语句此处用来简单写法,若无法理解,则可以写成以下形式,易于理解
* if(str.charAt(str_index) == target.charAt(target_index)){
* target_index++;
* str_index++;
* }else{
* str_index++;
* }
*/
}
//比较结束后,下表索引 == 目标字符串长度,则是其子串
return target_index==target.length() ;
}
}