Skip to content

Commit b2009a8

Browse files
committed
Improved 3456
1 parent 4d6547b commit b2009a8

File tree

1 file changed

+30
-21
lines changed
  • src/main/java/g3401_3500/s3456_find_special_substring_of_length_k

1 file changed

+30
-21
lines changed
Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,45 @@
11
package g3401_3500.s3456_find_special_substring_of_length_k;
22

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%)
44

55
public class Solution {
66
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;
1017
}
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;
2227
break;
2328
}
2429
}
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 {
3040
return true;
3141
}
3242
}
33-
// ❌ No valid substring found
3443
return false;
3544
}
3645
}

0 commit comments

Comments
 (0)