Home >Backend Development >PHP Tutorial >Find Longest Special Substring That Occurs Thrice I
2981. Find Longest Special Substring That Occurs Thrice I
Difficulty: Medium
Topics: Hash Table, String, Binary Search, Sliding Window, Counting
You are given a string s that consists of lowercase English letters.
A string is called special if it is made up of only a single character. For example, the string "abc" is not special, whereas the strings "ddd", "zz", and "f" are special.
Return the length of the longest special substring of s which occurs at least thrice, or -1 if no special substring occurs at least thrice.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can use a brute force approach due to the small constraints of s (length of up to 50). We'll:
Let's implement this solution in PHP: 2981. Find Longest Special Substring That Occurs Thrice I
Explanation:
- Outer Loop: We iterate over the possible lengths of substrings, starting with the longest. This ensures we return the longest special substring as soon as we find it.
- Sliding Window: For each substring length, we use a sliding window approach to extract all substrings of that length.
- Counting Substrings: We use an associative array ($countMap) to store and count occurrences of each substring.
- Checking Special: A helper function isSpecial checks if the substring is made up of only one repeated character.
- Returning the Result: If a valid substring is found, we return its length; otherwise, we return -1.
Complexity
This brute force approach is feasible given the constraints (n <= 50).
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Find Longest Special Substring That Occurs Thrice I. For more information, please follow other related articles on the PHP Chinese website!