LeetCode --- 贪心算法 --- 392. 判断子序列

基本上目标串最坏要全部遍历一遍时间复杂度最坏O(n)

有用二分 动态感觉太麻烦。

最简单的就是双指针和IndexOf方法

双指针:

 public bool IsSubsequence(string s, string t)
        {
            var sIndex = 0;
            if (s.Length <= 0)
                return true;
            for (int i = 0; i < t.Length; i++)
            {
                if (s[sIndex] == t[i])
                {
                    if (sIndex == s.Length - 1)
                        return true;
                    sIndex++;
                }
            }

            return false;
        }

IndexOf方法:

官方文档

   public bool IsSubsequence1(string s, string t)
        {
            var index = -1;
            for (int i = 0; i < s.Length; i++)
            {
                index = t.IndexOf(s[i], index + 1);
                if (index == -1)
                {
                    return false;
                }
            }

            return true;
        }
发布了71 篇原创文章 · 获赞 89 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/u012371712/article/details/104204261