392. Is Subsequence(JAVA)

来源:互联网 发布:开淘宝店保证金怎么交 编辑:程序博客网 时间:2024/06/07 05:01

題目

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 sis 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).

Example 1:
s = "abc"t = "ahbgdc"

Return true.

Example 2:
s = "axc"t = "ahbgdc"

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.



思路

兩層迴圈,外層迭代子串,內層迭代字符串。找出子串中的字母是否在字符串中,注意字符串中已被迭代過的部分不能再次迭代。





代碼

class Solution {
    public boolean isSubsequence(String s, String t) {
        int index = -1, i, j;
        for (i = 0; i < s.length(); i++) {
            for (j = index+1; j < t.length(); j++) {
                if (s.charAt(i) == t.charAt(j)) {
                    index = j;
                    break;
                }
            }
            if (j == t.length()) {
                break;
            }
        }
        if (i != s.length()) {
            return false;
        }
        else {
            return true;
        }
    }
}







感想

超級簡單的一道題……不是很能理解通過率為啥這麼低。