Lintcode 1263. Is Subsequence
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).
public boolean isSubsequence(String s, String t) {
// Write your code here
if (s.length() == 0)
return true;
StringBuilder sbs = new StringBuilder(s);
StringBuilder sbt = new StringBuilder(t);
int j = 0;
for (int i = 0; i < t.length(); i++) {
if (j == sbs.length())
return true;
if (t.charAt(i) == s.charAt(j)){
j++;
}
}
return j == s.length();
}
public boolean isSubsequence2(String s, String t) {
// Write your code here
int index = 0;
for (int i = 0; i < s.length(); i++) {
index = t.indexOf(s.charAt(i), index);
if (index < 0) return false;
index++;
}
return true;
}
要在不擾亂原有順序的情況下檢視是否是子序列,採取的貪心策略就是遍歷原string,兩個程式碼思路基本一樣,一個是從原序列的角度出發,一個是從子序列的角度出發。但是dalao的寫法更簡潔,更值得學習借鑑,從子序列的角度出發,通過indexof的第二個引數防止打亂順序,並使得在前一個查詢到的字母基礎上繼續查詢
相關文章
- LintCode-Longest Increasing Subsequence
- LintCode-Longest Common Subsequence
- 【Lintcode】398. Longest Continuous Increasing Subsequence II
- [LintCode] Longest Increasing Subsequence 最長遞增子序列
- Missing Subsequence Sum
- LeetCode #392: Is SubsequenceLeetCode
- Algorithm for Maximum Subsequence Sum zGo
- leetcode392. Is SubsequenceLeetCode
- [atcoder 349] [F - Subsequence LCM]
- B. Missing Subsequence Sum
- Leetcode: Arithmetic Slices II - SubsequenceLeetCode
- LeetCode-Wiggle SubsequenceLeetCode
- LeetCode-Longest Increasing SubsequenceLeetCode
- LeetCode-Increasing Triplet SubsequenceLeetCode
- CF1580D Subsequence 題解
- [LeetCode] 727. Minimum Window SubsequenceLeetCode
- 【LeetCode】Increasing Triplet Subsequence(334)LeetCode
- CF163A Substring and Subsequence 題解
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- [ARC186E] Missing Subsequence 題解
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Word SegmentationSegmentation
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree
- LintCode-Partition Array
- LintCode-Subarray Sum
- LintCode-Majority Number
- LintCode-A+B Problem
- LintCode-BackPack II
- LintCode-Previous Permuation