|
1 | 1 | package g3401_3500.s3456_find_special_substring_of_length_k;
|
2 | 2 |
|
3 |
| -// #Easy #2025_02_16_Time_1_ms_(100.00%)_Space_42.04_MB_(100.00%) |
| 3 | +// #Easy #2025_02_16_Time_0_ms_(100.00%)_Space_42.05_MB_(100.00%) |
4 | 4 |
|
5 | 5 | public class Solution {
|
6 | 6 | public boolean hasSpecialSubstring(String s, int k) {
|
7 |
| - // 🚫 If string is smaller than k, no valid substring exists |
8 |
| - if (s.length() < k) { |
9 |
| - return false; |
| 7 | + if (s.length() == k) { |
| 8 | + if (k == 1) { |
| 9 | + return true; |
| 10 | + } |
| 11 | + for (int i = 0; i < k - 1; i++) { |
| 12 | + if (s.charAt(i) != s.charAt(i + 1)) { |
| 13 | + return false; |
| 14 | + } |
| 15 | + } |
| 16 | + return true; |
10 | 17 | }
|
11 |
| - // 🔍 Iterate through all possible substrings of length k |
12 |
| - for (int i = 0; i <= s.length() - k; i++) { |
13 |
| - // 🧮 Count consecutive identical characters |
14 |
| - int count = 1; |
15 |
| - // ✅ Check if all k characters in the substring are the same |
16 |
| - for (int j = i; j < i + k - 1; j++) { |
17 |
| - if (s.charAt(j) == s.charAt(j + 1)) { |
18 |
| - // ➕ Increase count if consecutive characters are the same |
19 |
| - count++; |
20 |
| - } else { |
21 |
| - // ❌ Break if mismatch occurs |
| 18 | + int start = 0; |
| 19 | + int end = k; |
| 20 | + while (end <= s.length()) { |
| 21 | + boolean flag = false; |
| 22 | + for (int i = start; i < end - 1; i++) { |
| 23 | + if (s.charAt(i) != s.charAt(i + 1)) { |
| 24 | + start++; |
| 25 | + end++; |
| 26 | + flag = true; |
22 | 27 | break;
|
23 | 28 | }
|
24 | 29 | }
|
25 |
| - // 🔎 Ensure the substring is not part of a larger group |
26 |
| - if (count == k |
27 |
| - && (i == 0 || s.charAt(i - 1) != s.charAt(i)) |
28 |
| - && (i + k == s.length() || s.charAt(i + k) != s.charAt(i))) { |
29 |
| - // 🎯 Found a valid special substring |
| 30 | + if (flag) { |
| 31 | + continue; |
| 32 | + } |
| 33 | + if (start - 1 >= 0 && s.charAt(start) == s.charAt(start - 1)) { |
| 34 | + start++; |
| 35 | + end++; |
| 36 | + } else if (end < s.length() && s.charAt(end) == s.charAt(end - 1)) { |
| 37 | + start++; |
| 38 | + end++; |
| 39 | + } else { |
30 | 40 | return true;
|
31 | 41 | }
|
32 | 42 | }
|
33 |
| - // ❌ No valid substring found |
34 | 43 | return false;
|
35 | 44 | }
|
36 | 45 | }
|
0 commit comments