forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Largest Number After Mutating Substring.java
38 lines (35 loc) · 1.31 KB
/
Largest Number After Mutating Substring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public String maximumNumber(String num, int[] change) {
int i=0, n=num.length(), startIndex=-1, substringLength=0;
// traverse through each digit in the input string
while(i<n) {
int digit=num.charAt(i)-48;
// when we encounter a digit which has greater change
if(change[digit] > digit) {
startIndex = i;
// keep on replacing subsequent characters with with the change if they also have greater change
while(i<n) {
digit=num.charAt(i)-48;
if(change[digit] < digit) {
break;
}
i+=1;
}
substringLength = i-startIndex;
break;
}
i+=1;
}
// Note: Using String Builder to ensure linear time complexity as java strings are immutable
StringBuilder result=new StringBuilder("");
for(int j=0; j<n; j++) {
int digit=num.charAt(j)-48;
if(j>=startIndex && j<startIndex+substringLength) {
result.append(change[digit]);
} else {
result.append(digit);
}
}
return result.toString();
}
}