Leetcode 3083. Existence of a Substring in a String and Its Reverse
Given two strings s1
and s2
, write a function to check if there exists a substring in s1
that is equal to s2
or its reverse. You need to return true
if such a substring exists in s1
; otherwise, return false
.
s1
and s2
be empty? If so, what should be the output?s1
and s2
?s2
: Store the reverse of s2
.s1
to check if s2
or its reverse appears as substrings.contains
method provided by Java’s String class for efficient substring searching.s2
where n
is the length of s2
.m
is the length of s1
and n
is the length of s2
. However, the average complexity of the .contains
method tends to be more efficient due to internal optimizations.public class SubstringReverseCheck {
public boolean checkSubstring(String s1, String s2) {
if (s1 == null || s2 == null) return false;
String s2Reversed = new StringBuilder(s2).reverse().toString();
boolean containsS2 = s1.contains(s2);
boolean containsS2Reversed = s1.contains(s2Reversed);
return containsS2 || containsS2Reversed;
}
public static void main(String[] args) {
SubstringReverseCheck checker = new SubstringReverseCheck();
// Test cases
System.out.println(checker.checkSubstring("abcdefg", "cde")); // true
System.out.println(checker.checkSubstring("abcdefg", "edc")); // true
System.out.println(checker.checkSubstring("abcdefg", "xyz")); // false
System.out.println(checker.checkSubstring("abcdefg", "")); // true, empty is considered a substring
}
}
s2
.contains
Method: Searches for the presence of s2
or its reverse in s1
.true
if either s2
or its reverse is found in s1
.This code efficiently uses built-in Java methods to achieve the desired functionality, balancing readability and performance.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?