Lintcode 1263. Is Subsequence

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and tt is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).

public boolean isSubsequence(String s, String t) {
    // Write your code here
    if (s.length() == 0)
        return true;

    StringBuilder sbs = new StringBuilder(s);
    StringBuilder sbt = new StringBuilder(t);

    int j = 0;
    for (int i = 0; i < t.length(); i++) {
        if (j == sbs.length())
            return true;
        if (t.charAt(i) == s.charAt(j)){
            j++;
        }
    }
    return j == s.length();
}

public boolean isSubsequence2(String s, String t) {
    // Write your code here
    int index = 0;
    for (int i = 0; i < s.length(); i++) {
        index = t.indexOf(s.charAt(i), index);
        if (index < 0) return false;
        index++;
    }

    return true;


}

 

要在不扰乱原有顺序的情况下查看是否是子序列,采取的贪心策略就是遍历原string,两个代码思路基本一样,一个是从原序列的角度出发,一个是从子序列的角度出发。但是dalao的写法更简洁,更值得学习借鉴,从子序列的角度出发,通过indexof的第二个参数防止打乱顺序,并使得在前一个查找到的字母基础上继续查找

猜你喜欢

转载自blog.csdn.net/qq_38702697/article/details/82956781