If any substring of length 2 in s is also present in the reverse of s, then there is an overlap. We can collect all substrings of length 2 from s and from reverse(s), and check for intersection.
classSolution {
public:bool hasSubstringInReverse(string s) {
if (s.size() <2) return false;
unordered_set<string> subs, revsubs;
for (int i =0; i +1< s.size(); ++i) subs.insert(s.substr(i, 2));
reverse(s.begin(), s.end());
for (int i =0; i +1< s.size(); ++i) revsubs.insert(s.substr(i, 2));
for (auto& sub : subs) if (revsubs.count(sub)) return true;
return false;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicbooleanhasSubstringInReverse(String s) {
if (s.length() < 2) returnfalse;
Set<String> subs =new HashSet<>();
Set<String> revsubs =new HashSet<>();
for (int i = 0; i + 1 < s.length(); ++i) subs.add(s.substring(i, i+2));
StringBuilder sb =new StringBuilder(s).reverse();
for (int i = 0; i + 1 < s.length(); ++i) revsubs.add(sb.substring(i, i+2));
for (String sub : subs) if (revsubs.contains(sub)) returntrue;
returnfalse;
}
}
1
2
3
4
5
6
7
8
classSolution:
defhasSubstringInReverse(self, s: str) -> bool:
if len(s) <2:
returnFalse subs = set(s[i:i+2] for i in range(len(s)-1))
rev = s[::-1]
revsubs = set(rev[i:i+2] for i in range(len(rev)-1))
returnnot subs.isdisjoint(revsubs)
1
2
3
4
5
6
7
8
9
10
use std::collections::HashSet;
impl Solution {
pubfnhas_substring_in_reverse(s: String) -> bool {
if s.len() <2 { returnfalse; }
let subs: HashSet<_>= s.as_bytes().windows(2).map(|w| w.to_vec()).collect();
let rev: Vec<u8>= s.bytes().rev().collect();
let revsubs: HashSet<_>= rev.windows(2).map(|w| w.to_vec()).collect();
subs.intersection(&revsubs).next().is_some()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
hasSubstringInReverse(s: string):boolean {
if (s.length<2) returnfalse;
constsubs=newSet<string>();
for (leti=0; i+1<s.length; ++i) subs.add(s.substring(i, i+2));
constrev=s.split('').reverse().join('');
constrevsubs=newSet<string>();
for (leti=0; i+1<rev.length; ++i) revsubs.add(rev.substring(i, i+2));
for (constsubofsubs) if (revsubs.has(sub)) returntrue;
returnfalse;
}
}