String 检查一个字符串是否是另一个字符串的子序列的更好方法是什么
//方法1 //检查s1是否为s2的子序列(| s1 |<| s2 |)String 检查一个字符串是否是另一个字符串的子序列的更好方法是什么,string,algorithm,String,Algorithm,//方法1 //检查s1是否为s2的子序列(| s1 |
公共静态布尔isSubseq1(字符串s1、字符串s2){
int指数=-1;
对于(int i=0;i
//方法2
//检查A是否为B的子序列(|B |>=|A |)
public静态布尔值isSubseq2(字符串B、字符串A){
int j=0;
int n=B.长度();
int m=A.长度();
//遍历str2和str1,并进行比较
//具有第一个字符的str2的当前字符
//str1的不匹配字符(如果匹配)
//然后进入str1
对于(int i=0;i
我知道的事情:
第二种方法来自Geeksforgeks这两种方法都有
O(n)
最佳和最坏情况的时间复杂度
在这两种方法中,较大的字符串只遍历一次,因为在第一种方法中,s1.indexOf
本身遍历字符串
此外,您的解决方案也会在最坏的情况下运行,因为您从不在大字符串中检查同一字符两次,明智地使用索引
避免检查不再有趣的前缀可以确保(1)
(1) 假设
indexOf()
的实现是有效的,并且不会在第一个索引之前遍历元素。也许可以帮助您?
public static boolean isSubseq1(String s1, String s2) {
int index = -1;
for( int i = 0; i < s2.length(); i++) {
index = s1.indexOf(s2.charAt(i), index + 1);
if(index == -1)
return false;
}
return true;
}
public static boolean isSubseq2(String B, String A) {
int j = 0;
int n = B.length();
int m = A.length();
// Traverse str2 and str1, and compare
// current character of str2 with first
// unmatched char of str1, if matched
// then move ahead in str1
for (int i = 0; i < n && j < m; i++)
if (A.charAt(j) == B.charAt(i))
j++;
// If all characters of str1 were found
// in str2
return (j == m);
}