方法一:(自己写的)
class Solution {
public boolean isSubsequence(String s, String t) {
char[] sc=s.toCharArray();
char[] tc=t.toCharArray();
int i=0,j=0;
while(i<sc.length && j<tc.length) {
if(sc[i]==tc[j]) {
i++;
j++;
}else {
j++;
}
}
return i==sc.length;
}
}
再简洁一点:
class Solution {
public boolean isSubsequence(String s, String t) {
char[] sc=s.toCharArray();
char[] tc=t.toCharArray();
int i=0,j=0;
while(i<sc.length && j<tc.length) {
if(sc[i]==tc[j]) {
i++;
}
j++;
}
return i==sc.length;
}
}
方法二:
class Solution {
public boolean isSubsequence(String s, String t) {
int index=-1;
for(char c : s.toCharArray()) {
index=t.indexOf(c, index+1);
if(index==-1) {
return false;
}
}
return true;
}
}
注意indexOf()方法的使用:
- public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
- int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。c