Largest Number After Mutating Substring LeetCode solution in Java

1
class Solution {
2
public String maximumNumber(String num, int[] change) {
3
int i = 0, n = num.length(), startIndex = -1, substringLength = 0;
4

5
// traverse through each digit in the input string
6
while (i < n) {
7
int digit = num.charAt(i) - 48;
8
// when we encounter a digit which has greater change
9
if (change[digit] > digit) {
10
startIndex = i;
11
// keep on replacing subsequent characters with with the change if they also have greater
12
// change
13
while (i < n) {
14
digit = num.charAt(i) - 48;
15
if (change[digit] < digit) {
16
break;
17
}
18
i += 1;
19
}
20
substringLength = i - startIndex;
21
break;
22
}
23
i += 1;
24
}
25

26
// Note: Using String Builder to ensure linear time complexity as java strings are immutable
27
StringBuilder result = new StringBuilder("");
28
for (int j = 0; j < n; j++) {
29
int digit = num.charAt(j) - 48;
30
if (j >= startIndex && j < startIndex + substringLength) {
31
result.append(change[digit]);
32
} else {
33
result.append(digit);
34
}
35
}
36

37
return result.toString();
38
}
39
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0