资讯专栏INFORMATION COLUMN

[LeetCode/LintCode] Is Subsequence

terasum / 2183人阅读

Problem

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?

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

https://leetcode.com/problems...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76980.html

相关文章

  • [LeetCode/LintCode] Top K Frequent Words

    LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...

    0x584a 评论0 收藏0
  • [LeetCode/LintCode] Construct the Rectangle

    Problem For a web developer, it is very important to know how to design a web pages size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose l...

    sf_wangchong 评论0 收藏0
  • [LeetCode/LintCode] First Bad Version

    摘要:分析最后一次循环的时刻当与相差小于时,总是那么如果是,下一次直接跳出循环,返回当与相差大于时,是,变成,如果是,循环结束的条件将是循环结束,返回 Problem The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case,...

    lowett 评论0 收藏0
  • [LeetCode/LintCode] Valid Palindrome

    Valid Palindrome Problem Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Example A man, a plan, a canal: Panama is a palindrome. race a ca...

    Ververica 评论0 收藏0
  • [LeetCode/LintCode] Sentence Similarity

    Problem Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For example, great acting skills a...

    dreamtecher 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<