zoukankan      html  css  js  c++  java
  • Leetcode392. Is Subsequence

    Description
    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.

    My program:

    从s和t的首端开始遍历比较字符是否相等即可,如果不等,则增加在t中的下标j位置;如果相等,则同时增加s中下标i和t中下标j。如果t中的指标位置增长到了t的末尾,而s中的指标还没有增长的末尾,则返回false。如果s中的指标先增长到了末尾,则返回true。

    class Solution {
    public:
        bool isSubsequence(string s, string t) {
            int i = 0, j = 0;
            if (s.empty()) return true;
            while(i<s.size() && j<t.size())
            {
                if(s[i] == t[j])
                {
                    ++i;
                    ++j;
                }
                else
                    ++j;
            }
            if (i<s.size()) return false;
            else return true;
        }
    };

    Simple C++ code:

    bool isSubsequence(string s, string t) {
            int si= 0;
            for(int ti = 0; ti < t.size() && si < s.size(); ti++) {
                if(t[ti] == s[si]) si++;
            }
            return si == s.size();
        }
  • 相关阅读:
    LA 6891 Money Transfers(最短路)
    Gym
    UVa 1662 Brackets Removal
    Gym 101334F Feel Good
    Gym 101334E Exploring Pyramids(dp+乘法原理)
    POJ 2112 Optimal Milking(二分+最大流)
    POJ 2115 C Looooops(模线性方程)
    UVa 11552 最小的块数(序列划分模型:状态设计)
    UVa 10534 波浪子序列(快速求LIS)
    UVa 10891 Sum游戏
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391349.html
Copyright © 2011-2022 走看看