392. Is Subsequence
来源:互联网 发布:淘宝怎么设置地区运费 编辑:程序博客网 时间:2024/05/16 19:29
题目描述
题意分析
给两个字符串s和t, 判断s是不是t的子序列(不连续)
follow-up, 如果s有很多个, 怎样处理?
算法分析
s和t都扫一遍就好了..
实现
class Solution {public: bool isSubsequence(string s, string t) { int j = 0, i = 0, slen = s.size(), tlen = t.size(); while (i < tlen && j < slen) if (t[i++] == s[j]) j++; return (j > (slen-1)); } };
关于follow-up
扫一遍t, 将各个字母出现过的位置先后存在一个查询表里面,以字母为索引,
对每个s, 扫一遍, 对每个字符在查询表中能否找到符合条件的最小位置, 此时由于查询表是有序的,所以可以用二分查找
例子如下
代码参考:(来自cdai )
public boolean isSubsequence(String s, String t) { List<Integer>[] idx = new List[256]; // Just for clarity for (int i = 0; i < t.length(); i++) { if (idx[t.charAt(i)] == null) idx[t.charAt(i)] = new ArrayList<>(); idx[t.charAt(i)].add(i); } int prev = 0; for (int i = 0; i < s.length(); i++) { if (idx[s.charAt(i)] == null) return false; // Note: char of S does NOT exist in T causing NPE int j = Collections.binarySearch(idx[s.charAt(i)], prev); if (j < 0) j = -j - 1; if (j == idx[s.charAt(i)].size()) return false; prev = idx[s.charAt(i)].get(j) + 1; } return true; }
阅读全文
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**
- dubbo+zookeeper+spring+springMVC+mybatis的使用
- Vue 中的 v-cloak 解读
- 物联网技术未来的路
- Week Four
- MyBatis Mapper XML文件详解
- 392. Is Subsequence
- 第五周项目三
- C/C++ 第五周线性表 项目(三)括号的匹配
- 向QWidget中添加图片,并使图片随窗体大小缩放
- jquery.form.js的ajax提交,CKEditor编辑器内容丢失问题的解决方法!
- 欢迎使用CSDN-markdown编辑器
- 微信JSSDK-php-签名实现
- 第十二周项目1-验证算法(1)
- eclipse用户名的设置