題目


Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

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

Example 1:

1Input: s = "abc", t = "ahbgdc"
2Output: true

Example 2:

1Input: s = "axc", t = "ahbgdc"
2Output: false

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104
  • s and t consist only of lowercase English letters.

我的思路


這題我就比較直觀, loop 一遍 t,用一個 Varabile 去紀錄現在第幾個字元在 String s 裡面已經被找到了。loop 結束時,確實是否找到的數量等於 String s 的長度,如果是返回 true 否則返回 false

程式碼


 1class Solution {
 2    public boolean isSubsequence(String s, String t) {
 3        if (s.isEmpty()) {
 4            return true;
 5        }
 6        
 7        char[] sCharArray = s.toCharArray();
 8        char[] tCharArray = t.toCharArray();
 9        int sPosition = 0;
10        
11        for(int i = 0; i < t.length(); i++) {
12           if (tCharArray[i] == sCharArray[sPosition]) {
13               sPosition++;
14           }
15           
16            if (sPosition == s.length()) {
17                return true;
18            }
19        }
20        
21        return false;
22    }
23}