#leetCode刷题纪实 Day20

https://leetcode-cn.com/problems/is-subsequence/

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。

示例 1:
s = "abc", t = "ahbgdc"

返回 true.

示例 2:
s = "axc", t = "ahbgdc"

返回 false.

 

小菜鸡的尝试:

一开始以为是KMP,仔细一读,觉得这应该是一个很明显的贪心。于是遍历父串,如果字串的当前字符和父串的当前字符匹配,则两者都向后移一位;如果不匹配则只有父串向后移一位。时间复杂度应该是O(m+n)

 1 class Solution {
 2 public:
 3     bool isSubsequence(string s, string t) {
 4         int curr = 0;
 5         int sSize = s.length();
 6         int tSize = t.length();
 7         for (int i = 0; i < tSize; i ++) {
 8             if (s[curr] == t[i]) {
 9                 curr ++;
10                 continue;
11             } else {
12                 continue;
13             }
14         }
15         cout << curr << endl;
16         if (curr < sSize) {
17             return false;
18         }
19         return true;
20     }
21 };

本以为这样的时间复杂度应该不错了,但居然只打败了76%的人?好奇都是何方神圣

 

膜拜大佬代码:

 1 class Solution {
 2 public:
 3     bool isSubsequence(string s, string t) {
 4         const int t_size = t.size();
 5         const int s_size = s.size();
 6         int flag = 0;
 7         for (int i = 0; i < s_size; i++) { // 依次遍历s中的每一个字符
 8             const auto sc = s[i];
 9             while (flag < t_size && sc != t[flag]) // 从上次搜到的地方之后继续搜索当前要搜的字符
10                 flag++;
11             if (flag < t_size) {
12                 flag++;
13             } else { // 当前字符未搜到
14                 return false;
15             }
16         }
17         return true;
18     }
19 };

基本思路是一样的,省去了我最后一步循环外的判断。

 

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2019-11-19 22:40  xyy999  阅读(127)  评论(0)    收藏  举报