392. 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).
Example 1:
s = "abc", t = "ahbgdc"
Return true.
Example 2:
s = "axc", t = "ahbgdc"
Return false.
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

分析

给定两个字符串,判断一个字符串s是不是另外一个字符串t的子串,这里子串的意思是t删除一部分字符可以得到s,没有连续的要求。
因为没有连续的要求,所以只需要判断t中是否有s中所有字符且排列顺序一致,那就依次遍历就可以了。

代码

public boolean isSubsequence(String s, String t) {
    if(s.length() == 0) return true;
    int i = 0, j = 0;
    while(i < s.length() && j < t.length()){
        if(s.charAt(i) == t.charAt(j)){
            i++;
        }
        j++;
    }
    return i == s.length() ? true : false;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,846评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 海港飘雪后,天气明媚春。 波浪岸上涌,明月港湾照。 小船渔歌唱,海鲜味美纯。 感慨万千事,清闲独自找。
    小品味阅读 274评论 1 5
  • 春天里来百花香, 浪里格浪里格浪里格浪。 嗨,春光 十里桃花, 蜂舞蝶狂。 冰破冻,春水漾, 解舞风前, 春耕忙。...
    果然全身阅读 794评论 51 31
  • 饮泪莫提往事悲 琵琶曲弹孔雀飞 轻舟泛泛菩提叶 苦做生鲜乐即灰 望月叹吟束酒梅 俯首对饮三两杯 驾鹤南去摘星醉 登...
    叫我一土阅读 278评论 0 2