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

392. Is Subsequence

2017-05-21 19:25 295 查看
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
.
一开始我的思路是这样子的:在子序列s中每一个字符都在序列t里面去找,在实现的过程中怎么都找不到错误的地方在哪里。附上代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
int lengths = s.length();
int lengtht = t.length();
int i = 0;
int j = 0;
bool flag = false;
if(lengths == 0)
return true;
while(lengths)
{
while(lengtht)
{
if(s[i] == t[j])
{
flag = true;
break;
}
else
{
flag = false;

4000
j++;
}
lengtht--;
}
if(flag==false)
break;
lengths--;
i++;
}
return flag;
}
};

然后发现有一点逻辑错误,经修改后变成:
class Solution {
public:
    bool isSubsequence(string s, string t) {
        int lengths = s.length();
        int lengtht = t.length();
        int i = 0;
        int j = 0;
        bool flag = false;
        if(lengths == 0)
            return true;
        while(lengths)
        {
            flag = false;
            j = 0;
            while(lengtht)
            {
                if(s[i] == t[j])
                {
                    flag = true;
                    break;
                }
                j++;
                lengtht--;
            }
            if(flag==false)
                break;
            lengths--;
            i++;
        }
        return flag;
    }
};

发觉我的代码很啰嗦,于是简洁了一下:
class Solution {
public:
bool isSubsequence(string s, string t) {
int lengths = s.length();
int lengtht = t.length();
int i = 0;
int j = 0;
bool flag = false;
if(lengths == 0)
return true;
for(;i<lengths;i++)
{
flag = false;
for(j = 0;j<lengtht;j++)
{
if(s[i] == t[j])
{
flag = true;
break;
}
}
if(flag==false)
break;
}
return flag;
}
};
然后这个方法就卡在这个结果上:

Input:"acb""ahbgdc"

Output:true

Expected:false

我明白,原来我忽略了acb这个顺序,OH,MYGOD!!!!
最后我用了Python的all().可参考:all()
AC:
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
t = iter(t)
return all(c in t for c in s)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: