Check If String Is Transformable With Substring Sort Operations LeetCode solution in Java

1
class Solution {
2
public boolean isTransformable(String s, String t) {
3
if (!equal(s, t)) return false;
4
int[] countS = new int[10];
5
int[] countT = new int[10];
6
int[][] prev = new int[10][10];
7
int[][] after = new int[10][10];
8

9
for (int i = 0; i < s.length(); i++) {
10
int s1 = s.charAt(i) - '0';
11
int t1 = t.charAt(i) - '0';
12
countS[s1]++;
13
countT[t1]++;
14

15
// This step is to calculate how many digit less than s1/t1 occur before time i
16
// Store the frequency pair into 2-d array
17
for (int j = 0; j < s1; j++) {
18
if (countS[j] == 0) continue;
19
prev[j][s1] += countS[j];
20
}
21

22
for (int j = 0; j < t1; j++) {
23
if (countT[j] == 0) continue;
24
after[j][t1] += countT[j];
25
}
26
}
27

28
for (int i = 0; i <= 8; i++) {
29
for (int j = i + 1; j <= 9; j++) {
30
if (prev[i][j] == 0) continue;
31
// Check if any ascending pair's frequency has been reduced after modified.
32
if (after[i][j] < prev[i][j]) return false;
33
}
34
}
35

36
return true;
37
}
38

39
// Judge whether the two strings has the same digits
40
public boolean equal(String s, String t) {
41
char[] sc = s.toCharArray();
42
char[] tc = t.toCharArray();
43
Arrays.sort(sc);
44
Arrays.sort(tc);
45

46
for (int i = 0; i < s.length(); i++) {
47
if (sc[i] != tc[i]) return false;
48
}
49

50
return true;
51
}
52
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0