[LeetCode] Ambiguous Coordinates

816. Ambiguous Coordinates

We had some 2-dimensional coordinates, like “(1, 3)” or “(2, 0.5)”. Then, we removed all commas, decimal points, and spaces and ended up with the string s.

  • For example, “(1, 3)” becomes s = “(13)” and “(2, 0.5)” becomes s = “(205)”.
    Return a list of strings representing all possibilities for what our original coordinates could have been.

Our original representation never had extraneous zeroes, so we never started with numbers like “00”, “0.0”, “0.00”, “1.0”, “001”, “00.01”, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like “.1”.

The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)

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 {
vector<string> dnc(string s) {
if(s.back() == '0') {
if(s.length() > 1 and s[0] == '0') return {};
return {s};
}

vector<string> res;
deque<char> front, back(begin(s), end(s));

for(int i = 0; i < s.length(); i++) {
front.push_back(back.front()); back.pop_front();
if(front[0] == '0' and front.size() > 1) break;
if(!back.empty() and back.back() == '0') continue;

string f(begin(front), end(front));
string b(begin(back), end(back));

if(b.length() == 0) res.push_back(f);
else res.push_back(f + "." + b);
}
return res;
}
public:
vector<string> ambiguousCoordinates(string s) {
vector<string> res;
for(int i = 2; i < s.length() - 1; i++) {
auto l = s.substr(1, i - 1), r = s.substr(i, s.length() - 1 - i);
auto L = dnc(l), R = dnc(r);
for(auto& ll : L) {
for(auto& rr : R) {
res.push_back("(" + ll + ", " + rr +")");
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/ambiguous-coordinates/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.