[LeetCode] Existence of a Substring in a String and Its Reverse

3083. Existence of a Substring in a String and Its Reverse

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool isSubstringPresent(string s) {
unordered_set<string> us;
for(int i = 0; i < s.length() - 1; i++) {
string now = "";
now.push_back(s[i]);
now.push_back(s[i+1]);
us.insert(now);
}
reverse(begin(s), end(s));
for(int i = 0; i < s.length() - 1; i++) {
string now = "";
now.push_back(s[i]);
now.push_back(s[i+1]);
if(us.count(now)) return true;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/17/PS/LeetCode/existence-of-a-substring-in-a-string-and-its-reverse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.