2017网易---藏宝图

题目描述

牛牛拿到了一个藏宝图,顺着藏宝图的指示,牛牛发现了一个藏宝盒,藏宝盒上有一个机关,机关每次会显示两个字符串 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):
 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 }
View Code

 

posted on 2018-03-23 10:46  二十年后20  阅读(972)  评论(0编辑  收藏  举报

导航