您的位置:首页 > 产品设计 > UI/UE

392. Is Subsequence | LeetCode Dynamic Programming

2017-05-22 02:47 417 查看

Description

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 t. t 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).

Example 1:

s = “abc”, t = “ahbgdc”

Return true.

Example 2:

s = “axc”, t = “ahbgdc”

Return false.

Difficulty: Medium

Thinking

本题要求判断短字符串是不是长字符串的子序列。方法很简单,从s和t的首位开始遍历两字符串进行比较,当s中的字符与t中字符相同时,s与t字符数组的下标都加1;不相同时,s下标固定,t的坐标加1,直到相同。当t字符串的遍历坐标大于t的长度,而s串的遍历下表仍小于s长度时,说明s不是t的子序列,函数返回false。否则返回true。需要注意的是,当s为空串时,s一定是t的子序列,函数返回true。

Solution

class Solution {
public:
bool isSubsequence(string s, string t) {
int slen = s.size();
int tlen = t.size();
int j = 0, i = 0;
if(slen == 0) return true;
for(; i < slen; i++){
while(t[j] != s[i] && j < tlen) j++;
if(j >= tlen) return false;
j++;
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode string