判断子序列

此博客链接:https://www.cnblogs.com/ping2yingshi/p/13728786.html

判断子序列

题目链接:https://leetcode-cn.com/problems/is-subsequence/

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。

示例 1:
s = "abc", t = "ahbgdc"

返回 true.

示例 2:
s = "axc", t = "ahbgdc"

返回 false.

思路:

         说明:此题我没有看出来动态规划的思想呢,我想着取出自序列中的字符,然后到t中寻找,找到时(假设在t中的第m个位置找到),接着取子串中的第二个字符,在t中第m个后面的字符接着找。一开始使用两次循环,但是没有办法改变找到后,接着向后寻找的操作,后来又想着把for改成while写,还是没有想到怎么处理,看了别人的题解,感觉自己傻了,思路一样,而我还是不会写代码。

代码如下:

class Solution {
    public boolean isSubsequence(String s, String t) {
     
        int i=0;
        int j=0;
        while(j<t.length()&&i<s.length()){
            if(s.charAt(i)==t.charAt(j))
             {
                 i++;
             }
             j++;
        }
        if(i==s.length())   
           return true;
       else 
           return false;        
                       
             
    }
}

备注:

    一开始没有写对的代码

class Solution {
    public boolean isSubsequence(String s, String t) {
        char [] a=s.toCharArray();
        char[]  b= t.toCharArray();
        // int i=0;
        // int j=0;
        // while(i<a.length){
        //     if(a[i]==b[j])
        //      {
                
        //      }
        //      i++;
        //      j++;

        // }
                  
                       
             }
    }
}
出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/13728786.html