LeetCode/com/zerroi/leetcode/Three12/IsSubsequence.java

41 lines
1.4 KiB
Java
Raw Normal View History

2024-03-14 20:58:23 +08:00
package com.zerroi.leetcode.Three12;
public class IsSubsequence {
public static void main(String[] args) {
SolutionFirst solutionFirst = new SolutionFirst();
// boolean res = solutionFirst.isSubsequence("abc", "ahbgdc");
// boolean res = solutionFirst.isSubsequence("axc", "ahbgdc");
// boolean res = solutionFirst.isSubsequence("acb", "ahbgdc");
boolean res = solutionFirst.isSubsequence("", "");
System.out.println("res = " + res);
}
}
/*
* 给定字符串 s t 判断 s 是否为 t 的子序列
字符串的一个子序列是原始字符串删除一些也可以不删除字符而不改变剩余字符相对位置形成的新字符串例如"ace""abcde"的一个子序列"aec"不是
进阶
如果有大量输入的 S称作 S1, S2, ... , Sk 其中 k >= 10亿你需要依次检查它们是否为 T 的子序列在这种情况下你会怎样改变代码
* */
class SolutionFirst {
public boolean isSubsequence(String s, String t) {
int n1 = s.length();
int j = 0;
int count = 0;
for (int i = 0; i < n1; i++) {
while (j < t.length()) {
if (s.charAt(i) == t.charAt(j)) {
count ++;
j++;
break;
}
j++;
}
}
return count == s.length();
}
}