[LeetCode] 392. Is Subsequence Java

來源:互聯網
上載者:User

標籤:==   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.