3083. Existence of a Substring in a String and Its Reverse
Description
Given a string s
, find any substring of length 2
which is also present in the reverse of s
.
Return true
if such a substring exists, and false
otherwise.
Example 1:
Input: s = "leetcode"
Output: true
Explanation: Substring "ee"
is of length 2
which is also present in reverse(s) == "edocteel"
.
Example 2:
Input: s = "abcba"
Output: true
Explanation: All of the substrings of length 2
"ab"
, "bc"
, "cb"
, "ba"
are also present in reverse(s) == "abcba"
.
Example 3:
Input: s = "abcd"
Output: false
Explanation: There is no substring of length 2
in s
, which is also present in the reverse of s
.
Constraints:
1 <= s.length <= 100
s
consists only of lowercase English letters.
Solutions
Solution 1: Hash Table or Array
We can use a hash table or a two-dimensional array $st$ to store all substrings of length $2$ of the reversed string $s$.
Then we traverse the string $s$. For each substring of length $2$, we check whether it has appeared in $st$. If it has, we return true
. Otherwise, we return false
after the traversal.
The time complexity is $O(n)$ and the space complexity is $O(|\Sigma|^2)$. Here, $n$ is the length of the string $s$, and $\Sigma$ is the character set of the string $s$. In this problem, $\Sigma$ consists of lowercase English letters, so $|\Sigma| = 26$.
1 2 3 4 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|