【leedcode】392. Is Subsequence

来源:互联网 发布:淘宝火拼下架 编辑:程序博客网 时间:2024/06/07 05:48
题目:

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 s is 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).

分析:这道题目我选择遍历t,如果t[i]与s[j]相等,则j++。当s[j] == ‘\0’时即是true,若t[i] == ‘\0’则是false.。本来这道题是归在动态规划算法分类下的,我也想用动态规划的方法来解决,但是这样的遍历的方法是O(n)的时间复杂度,我觉得已经是一个很好的算法了,再者我想的动态规划算法的复杂度反而较高,所以我选择了这样的方法。

代码:

#include <iostream>
using namespace std;


class Solution {
public:
bool isSubsequence(string s, string t) {
if (s == "") return true;
int j = 0;
for (int i = 0; i < t.size(); i++) {
if (t[i] == s[j]) {
j++;
}
if (s[j] == '\0') {
return true;
}
}
return false;
}
};