392. Is Subsequence
来源:互联网 发布:java可变参数不传入 编辑:程序博客网 时间:2024/06/03 17:43
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; 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
最后我用了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)
阅读全文
0 0
- 392. Is Subsequence
- 392.[LeetCode] Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- LeetCode 392. Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- [LeetCode] 392. Is Subsequence
- 【leetcode】392. Is Subsequence
- 【LeetCode】392. Is Subsequence
- 【LeetCode】392. Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- Leetcode 392. Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- leetcode 392. Is Subsequence
- 392. Is Subsequence**
- c++ 文件操作
- JavaScript改变this指向的3种方法(代码说明)
- Java命令行参数类 Commons CLI使用
- 第7章 51DOS操作系统设计与实现
- [IDA*] BZOJ1085: [SCOI2005]骑士精神
- 392. Is Subsequence
- 查看IPC使用情况
- 链接————csapp
- zabbix-3.2 install-guide on ubuntu 14.04 server
- 第十三天:ArrayList的底层add方法原理,按自己理解重写了一下
- SecureCRT远程连接Linux---终端中文字符出现乱码的解决方式
- swift 学习笔记|Optional、?和!
- Monkey 压力测试
- jsp语法