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();
        }
  • 相关阅读:
    VirtualBox安装及使用说明和虚拟机安装XP系统图文教程
    jbpm入门样例
    39个让你受益的HTML5教程
    JAVA反射机制
    怎样学好C语言,一个成功人士的心得!
    golang使用pprof检查goroutine泄露
    GridView编辑删除操作
    初识Servlet
    严苛模式(StrictMode)
    严苛模式(StrictMode)
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391349.html
Copyright © 2011-2022 走看看