Featured image of post 392. 判断子序列

392. 判断子序列

题目描述

给定字符串 st ,判断 s 是否为 t 的子序列。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace""abcde" 的一个子序列,而 "aec" 不是)。

进阶:

如果有大量输入的 S,称作 S1, S2, … , Sk 其中 k >= 10 亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

示例 1:

  • 输入:s = “abc”, t = “ahbgdc”
  • 输出:true

示例 2:

  • 输入:s = “axc”, t = “ahbgdc”
  • 输出:false

提示:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 10^4
  • 两个字符串都只由小写字符组成。

解法一:双指针

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func isSubsequence(s string, t string) bool {
    if len(s) == 0 {
        return true
    }
    idx := 0
    for i := 0; i < len(t); i++ {
        if t[i] == s[idx] {
            idx++
        }
        if idx == len(s) {
            return true
        }
    }
    return false
}

解法二:动态规划

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
func isSubsequence(s string, t string) bool {
    n := len(t)
    if n == 0 {
        if len(s) == 0 {
            return true
        }
        return false
    }

    dp := make([][26]int, n)
    for i := 0; i < 26; i++ {
        dp[n-1][i] = n
    }
    dp[n-1][t[len(t)-1]-'a'] = n - 1
    for i := n - 2; i >= 0; i-- {
        for j := 0; j < 26; j++ {
            if t[i]-'a' == uint8(j) {
                dp[i][j] = i
            } else {
                dp[i][j] = dp[i+1][j]
            }
        }
    }

    next, idx := 0, 0
    for idx < len(s) && next < n {
        chN := s[idx] - 'a'
        if dp[next][chN] == n {
            return false
        }
        next = dp[next][chN] + 1
        idx++
    }
    return idx == len(s)
}

官方题解如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func isSubsequence(s string, t string) bool {
    n, m := len(s), len(t)
    f := make([][26]int, m + 1)
    for i := 0; i < 26; i++ {
        f[m][i] = m
    }
    for i := m - 1; i >= 0; i-- {
        for j := 0; j < 26; j++ {
            if t[i] == byte(j + 'a') {
                f[i][j] = i
            } else {
                f[i][j] = f[i + 1][j]
            }
        }
    }
    add := 0
    for i := 0; i < n; i++ {
        if f[add][int(s[i] - 'a')] == m {
            return false
        }
        add = f[add][int(s[i] - 'a')] + 1
    }
    return true
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/12 23:00:52
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计