Lintcode 1263. Is Subsequence

Vendredimatin發表於2018-10-07

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的第二個引數防止打亂順序,並使得在前一個查詢到的字母基礎上繼續查詢

相關文章