392.判断子序列
题目描述
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
s = “abc”, t = “ahbgdc”
返回 true.
示例 2:
s = “axc”, t = “ahbgdc”
返回 false.
题解
class Solution {
public boolean isSubsequence(String s, String t) {
//若s为空,直接返回true
if(s.isEmpty()) return true;
//字符串转换成字符数组,方便操作
char[] ch1 = s.toCharArray();
char[] ch2 = t.toCharArray();
boolean flag = false;
int i = 0,j = 0;
//遍历子串和长串,相同字符,则都继续向后遍历,不同则长串向后,子串不动,遍历一遍即可得出结果
while(i<s.length()){
while(j<t.length()){
if(ch1[i] == ch2[j]){
i++;
j++;
}else{
j++;
}
if(i==s.length()){
flag = true;
break;
}
}
break;
}
return flag;
}
}
题解改进
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0;
for (char ch : s.toCharArray()) {
while (i < t.length() && t.charAt(i) != ch) i++;
i++;
}
return i <= t.length() ? true : false;
}
}