Skip to content

Commit 184dcda

Browse files
authored
Create 2264-largest-3-same-digit-number-in-string.java
1 parent a08c7ee commit 184dcda

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* Problem: 2264. Largest 3-Same-Digit Number in String
3+
* Difficulty: Easy
4+
* URL: https://leetcode.com/problems/largest-3-same-digit-number-in-string/
5+
*
6+
* ---------------------
7+
* Approach 1: Brute Force (Substring + Parse)
8+
* ---------------------
9+
* - Iterate through the string and check if three consecutive characters are the same.
10+
* - If so, parse them as a number and track the maximum.
11+
*
12+
* Time Complexity: O(n)
13+
* Space Complexity: O(1)
14+
*/
15+
class Solution {
16+
public String largestGoodInteger(String num) {
17+
long max = Long.MIN_VALUE;
18+
for (int i = 0; i < num.length() - 2; i++) {
19+
if (num.charAt(i) == num.charAt(i + 1) &&
20+
num.charAt(i + 1) == num.charAt(i + 2)) {
21+
22+
long val = Long.parseLong(num.substring(i, i + 3));
23+
if (val > max) max = val;
24+
}
25+
}
26+
if (max == 0) return "000";
27+
return max > Long.MIN_VALUE ? String.valueOf(max) : "";
28+
}
29+
}
30+
31+
/**
32+
* ---------------------
33+
* Approach 2: Brute Force with Counting
34+
* ---------------------
35+
* - Iterate through the string with a counter for consecutive identical digits.
36+
* - When count reaches 3, update the max digit.
37+
* - Avoid parsing; directly compare characters for efficiency.
38+
*
39+
* Time Complexity: O(n)
40+
* Space Complexity: O(1)
41+
*/
42+
class Solution {
43+
public String largestGoodInteger(String num) {
44+
int count = 0;
45+
char max = ' ';
46+
char prev = ' ';
47+
48+
for (char ch : num.toCharArray()) {
49+
if (ch == prev) count++;
50+
else count = 1;
51+
52+
if (count == 3) {
53+
max = (char) Math.max(max, ch);
54+
}
55+
prev = ch;
56+
}
57+
return max == ' ' ? "" : String.valueOf(max).repeat(3);
58+
}
59+
}
60+
61+
/**
62+
* ---------------------
63+
* Approach 3: Optimal (Predefined Candidates)
64+
* ---------------------
65+
* - Pre-store all possible valid 3-digit identical numbers from largest to smallest.
66+
* - Check if the input contains each one; return the first match.
67+
* - Since the array is constant size (10 elements), this is very fast.
68+
*
69+
* Time Complexity: O(n) [10 × O(n) => O(n)]
70+
* Space Complexity: O(1)
71+
*/
72+
class Solution {
73+
public String largestGoodInteger(String num) {
74+
String[] candidates = { "999", "888", "777", "666", "555",
75+
"444", "333", "222", "111", "000" };
76+
for (String c : candidates) {
77+
if (num.contains(c)) return c;
78+
}
79+
return "";
80+
}
81+
}

0 commit comments

Comments
 (0)