標籤:== main english leetcode sequence 一個 判斷 span position
題目:
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 sis 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,求s是否是t中的一個序列。就是要判斷s中的每一個字元在t中是否順序存在。這道題是沒看答案作出的第一到貪心演算法的題。。。以上面的Example作分析,在t中先找到字元a,那麼在t中找到b,c的機率就更大;對於剩下的"bc",先在t中找到b,剩下的字元就越多,找到c的機率就越大。所以,這裡我們對於s中的每一個字元都盡量在t中先找到,那麼剩下的字元就越多,符合要求的機率就越大。
代碼:
public class Solution { public boolean isSubsequence(String s, String t) { int sLength=s.length();//s的長度 int tLength=t.length();//t的長度 int sIndex=0;//記錄找到了s的第幾個字元 int tIndex=0;//記錄遍曆到了t的第幾個字元 while(tIndex<tLength){//這裡用到的貪心演算法,就是在t中越先找到 s的字元 那麼在t中就更容易的找到 s剩下的字元 if(sIndex<sLength&&(s.charAt(sIndex)==t.charAt(tIndex))){//找到一個相等的字元就尋找s的下一個字元 sIndex++; } tIndex++; } if(sIndex==sLength){//從前往後在t中找到了s的所有字元 。所以存在 return true; } else{ return false; } }}
[LeetCode] 392. Is Subsequence Java