zoukankan      html  css  js  c++  java
  • leetcode -- 392 判断子序列

    题目描述:

    给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
    
    你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
    
    字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace""abcde"的一个子序列,而"aec"不是)。
    
    示例 1:
    s = "abc", t = "ahbgdc"
    
    返回 true.
    
    示例 2:
    s = "axc", t = "ahbgdc"
    
    返回 false.
    
    后续挑战 :
    
    如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

    菜死我了QAQ,上代码

    class Solution {
    public:
        bool isSubsequence(string s, string t) {
            if(s.length() == 1 && t.length() == 1 && s[0] != t[0])
            {
                return false;
            }
            if(s.length() == 0)
            return true;
            int a = 0;
            for(int i = 0 ; i < s.length() ;  i++)
            {
                
                if( a == 0 && i!=0)
                {
                    return false;
                }
                if( a == t.length())
                {
                    return false;
                }
                for(int j = a ; j < t.length() ; j ++)
                {
                    if(s[i] == t[j])
                    {
                        a = j+1;
                        break;
                    }
                    
                    else{
                        if(j == t.length()-1)
                        {
                            a = 0;
                        }
                        continue;
                    }
    
                
                }
                
             }
             if( a == 0 )
                {
                    return false;
                }
             return true; 
        }
    };

    以上是我写的代码,看了看官方题解.... orz

    class Solution {
    public:
        bool isSubsequence(string s, string t) {
            int n = s.length(), m = t.length();
            int i = 0, j = 0;
            while (i < n && j < m) {
                if (s[i] == t[j]) {
                    i++;
                }
                j++;
            }
            return i == n;
        }
    };
    
    作者:LeetCode-Solution
    链接:https://leetcode-cn.com/problems/is-subsequence/solution/pan-duan-zi-xu-lie-by-leetcode-solution/
  • 相关阅读:
    测试模式 windows2008 内部版本7601
    移动端UC /QQ 浏览器的部分私有Meta 属性
    正则表达式 正向预查 负向预查
    获取指定元素的某一个样式属性值
    把普通对象转换成json格式的对象
    求平均数-----类数组转换成数组
    轮播图
    倒计时
    JS 预解释相关理解
    ul ol di三者区别
  • 原文地址:https://www.cnblogs.com/wtzmz/p/13387400.html
Copyright © 2011-2022 走看看