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】398. Longest Continuous Increasing Subsequence II
- Missing Subsequence Sum
- leetcode392. Is SubsequenceLeetCode
- [atcoder 349] [F - Subsequence LCM]
- B. Missing Subsequence Sum
- [LeetCode] 727. Minimum Window SubsequenceLeetCode
- 673. Number of Longest Increasing Subsequence
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- [LeetCode] 674. Longest Continuous Increasing SubsequenceLeetCode
- CF163A Substring and Subsequence 題解
- 簡單dp -- Common Subsequence POJ - 1458
- CF1580D Subsequence 題解
- 【Leetcode】1081. Smallest Subsequence of Distinct CharactersLeetCode
- 【Leetcode】1673. Find the Most Competitive SubsequenceLeetCode
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- 【Lintcode】1189. Minesweeper
- 最長公共子序列 Longest Common Subsequence
- [ARC186E] Missing Subsequence 題解
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie
- 【Lintcode】1732. Snakes and Ladders
- 【Lintcode】1218. Number Complement
- 【Lintcode】1850. Pick ApplesAPP