leetcode判断子序列

在这里插入图片描述
直接上代码:

class Solution(object):
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        b=0
        for i in s:
            if i in t[b:]:
                a=t.index(i,b,)
                b=a+1
            else:
                return False
        return True
            

在看别人写的代码时,发现了一个比较好的例子:

class Solution(object):
    def isSubsequence(self, s, t):
        t = iter(t)
        return all(c in t for c in s)

仅仅添加两行代码就好了。这里iter()是生成一个迭代器,all()函数是用来判断里面的元素是否都为真,也就是s里面的元素是否都存在在t中。
当然,对于进阶的解决办法:创建一个矩阵,保存26个字母出现的位置。

class Solution {
public:
 bool isSubsequence(string s, string t) {
  t.insert(t.begin(), ' ');
  int len1 = s.size(), len2 = t.size();
  vector<vector<int> > dp(len2 , vector<int>(26, 0));
  for (char c = 'a'; c <= 'z'; c++) {
   int nextPos = -1; //表示接下来再不会出现该字符
   for (int i = len2 - 1; i>= 0; i--) {  //为了获得下一个字符的位置,要从后往前
    dp[i][c - 'a'] = nextPos;
    if (t[i] == c)
     nextPos = i;
   }
  }
  int index = 0;
  for (char c : s) {
   index = dp[index][c - 'a'];
   if (index == -1)
    return false;
  }
  return true;
 }
};
发布了29 篇原创文章 · 获赞 28 · 访问量 279

猜你喜欢

转载自blog.csdn.net/weixin_45398265/article/details/105129461
今日推荐