跳转至

3083. 字符串及其反转中是否存在同一子字符串

题目描述

给你一个字符串 s ,请你判断字符串 s 是否存在一个长度为 2 的子字符串,在 s 反转后的字符串中也出现。

如果存在这样的子字符串,返回 true;如果不存在,返回 false

 

示例 1:

输入:s = "leetcode"

输出:true

解释:子字符串 "ee" 的长度为 2,它也出现在 reverse(s) == "edocteel" 中。

示例 2:

输入:s = "abcba"

输出:true

解释:所有长度为 2 的子字符串 "ab""bc""cb""ba" 也都出现在 reverse(s) == "abcba" 中。

示例 3:

输入:s = "abcd"

输出:false

解释:字符串 s 中不存在满足「在其反转后的字符串中也出现」且长度为 2 的子字符串。

 

提示:

  • 1 <= s.length <= 100
  • 字符串 s 仅由小写英文字母组成。

解法

方法一:哈希表或数组

思考

\(n \le 100\),长度为 \(2\) 的子串种类有限。存在某个长为 \(2\) 的片段同时出现在 \(s\)\(s\) 的反转中即可。

先把反转串的所有相邻对放进集合,再扫原串的相邻对做查询。

一次建集、一次查询,均为线性。

我们可以用一个哈希表或者二维数组 \(st\) 来存储字符串 \(s\) 反转后的所有长度为 \(2\) 的子字符串。

然后我们遍历字符串 \(s\),对于每一个长度为 \(2\) 的子字符串,我们判断它是否在 \(st\) 中出现过,是则返回 true。否则,遍历结束后返回 false

时间复杂度 \(O(n)\),空间复杂度 \(O(|\Sigma|^2)\)。其中 \(n\) 为字符串 \(s\) 的长度;而 \(\Sigma\) 为字符串 \(s\) 的字符集,本题中 \(\Sigma\) 为小写英文字母,所以 \(|\Sigma| = 26\)

1
2
3
4
class Solution:
    def isSubstringPresent(self, s: str) -> bool:
        st = {(a, b) for a, b in pairwise(s[::-1])}
        return any((a, b) in st for a, b in pairwise(s))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public boolean isSubstringPresent(String s) {
        boolean[][] st = new boolean[26][26];
        int n = s.length();
        for (int i = 0; i < n - 1; ++i) {
            st[s.charAt(i + 1) - 'a'][s.charAt(i) - 'a'] = true;
        }
        for (int i = 0; i < n - 1; ++i) {
            if (st[s.charAt(i) - 'a'][s.charAt(i + 1) - 'a']) {
                return true;
            }
        }
        return false;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    bool isSubstringPresent(string s) {
        bool st[26][26]{};
        int n = s.size();
        for (int i = 0; i < n - 1; ++i) {
            st[s[i + 1] - 'a'][s[i] - 'a'] = true;
        }
        for (int i = 0; i < n - 1; ++i) {
            if (st[s[i] - 'a'][s[i + 1] - 'a']) {
                return true;
            }
        }
        return false;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
func isSubstringPresent(s string) bool {
    st := [26][26]bool{}
    for i := 0; i < len(s)-1; i++ {
        st[s[i+1]-'a'][s[i]-'a'] = true
    }
    for i := 0; i < len(s)-1; i++ {
        if st[s[i]-'a'][s[i+1]-'a'] {
            return true
        }
    }
    return false
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function isSubstringPresent(s: string): boolean {
    const st: boolean[][] = Array.from({ length: 26 }, () => Array(26).fill(false));
    for (let i = 0; i < s.length - 1; ++i) {
        st[s.charCodeAt(i + 1) - 97][s.charCodeAt(i) - 97] = true;
    }
    for (let i = 0; i < s.length - 1; ++i) {
        if (st[s.charCodeAt(i) - 97][s.charCodeAt(i + 1) - 97]) {
            return true;
        }
    }
    return false;
}

评论