• 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();
        }
  • 相关阅读:
    freebsd ports update url
    Cisco交换机里IP和MAC地址互查找出对应端口
    实现不同vlan间的相互通信方法一:单臂路由
    文件共享③Samba实例
    RHEL6基础四十九之RHEL文件(夹)权限进阶篇
    windows下查找指定端口被哪个程序占用
    DNSmasq – 配置DNS和DHCP
    dnsmasq多vlan配置
    dnsmasq.conf 配置
    windows2003 DHCP中批处理绑定IP与MAC
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391349.html
Copyright © 2020-2023  润新知