Ambiguous Coordinates LeetCode solution in Java

1
class Solution {
2
public List<String> ret;
3
public List<String> ans;
4

5
public List<String> ambiguousCoordinates(String s) {
6
ret = new ArrayList<>();
7
ans = new ArrayList<>();
8
String start = s.substring(0, 2);
9
util(s, 1);
10
fun();
11
return ans;
12
}
13

14
// putting comma
15
void util(String s, int idx) {
16
if (idx == s.length() - 2) {
17
return;
18
}
19

20
String ns = s.substring(0, idx + 1) + ", " + s.substring(idx + 1);
21
ret.add(ns);
22
util(s, idx + 1);
23
}
24

25
// helper function for puting decimals after comma
26
void fun() {
27
for (String s : ret) {
28
int cIndex = 0;
29
for (int i = 0; i < s.length(); i++) {
30
if (s.charAt(i) == ',') {
31
cIndex = i;
32
break;
33
}
34
}
35
String a = s.substring(1, cIndex);
36
String b = s.substring(cIndex + 2, s.length() - 1);
37
List<String> n1 = dot(a);
38
List<String> n2 = dot(b);
39
if (n1 == null || n2 == null) { // invalid strings
40
continue;
41
} else { // valid strings
42
for (String fir : n1) {
43
for (String sec : n2) {
44
ans.add("(" + fir + ", " + sec + ")");
45
}
46
}
47
}
48
}
49
}
50

51
// putting decimal point
52
List<String> dot(String n) {
53
List<String> li = new ArrayList<>();
54
if (n.length() == 1) {
55
li.add(n);
56
} else {
57

58
// just checking for first and last zeroes and making conditions accordingly
59

60
if (n.charAt(n.length() - 1) == '0') {
61
if (n.charAt(0) == '0') {
62
return null;
63
} else {
64
li.add(n);
65
}
66
} else if (n.charAt(0) == '0') {
67
li.add("0." + n.substring(1));
68
} else {
69
for (int i = 0; i < n.length() - 1; i++) {
70
li.add(n.substring(0, i + 1) + "." + n.substring(i + 1));
71
}
72
li.add(n); // without any decimal
73
}
74
}
75
return li;
76
}
77
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0