題目描述
牛牛拿到了一個藏寶圖,順着藏寶圖的指示,牛牛發現了一個藏寶盒,藏寶盒上有一個機關,機關每次會顯示兩個字符串 s 和 t,根據古老的傳說,牛牛須要每次都回答 t 是不是 s 的子序列。注意,子序列不要求在原字符串中是連續的,例如串 abc,它的子序列就有 {空串, a, b, c, ab, ac, bc, abc} 8 種。
輸入描述:
每一個輸入包含一個測試用例。每一個測試用例包含兩行長度不超過 10 的不包含空格的可見 ASCII 字符串。
輸出描述:
輸出一行 「Yes」 或者 「No」 表示結果。
示例1
輸入
x.nowcoder.com ooo
輸出
Yes
題目連接
法一:數據較小,兩層for循環,外層循環是子序列,內層循環是母串,根據子序列的每一個字符,去匹配母串中的字符,若是匹配,則子序列和母串同時後移,若是不匹配,則母串後移,直到匹配,計數匹配的字符個數,
最後與子序列進行比較。代碼以下(耗時7ms):
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
1 public class Main { 2 3 public static void main(String[] args) throws IOException { 4 BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 5 String s = in.readLine(); 6 String t = in.readLine(); 7 int len_s = s.length(), len_t = t.length(); 8 if(len_s < len_t) { 9 System.out.println("No"); 10 return; 11 } 12 int j = 0, i = 0, cnt = 0; 13 for(i = 0; i < len_t; i++) { 14 //遍歷母串 15 while(j < len_s) { 16 //若是匹配,同時後移子序列和母串 17 if(t.charAt(i) == s.charAt(j)) { 18 j++; 19 cnt++; 20 break; 21 } 22 //若是不匹配,則後移母串 23 j++; 24 } 25 } 26 if(cnt == len_t) { 27 System.out.println("Yes"); 28 } 29 else { 30 System.out.println("No"); 31 } 32 } 33 34 }