816. Ambiguous Coordinates**

​https://leetcode.com/problems/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. 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 less 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. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)

Example 1:

Input: "(123)"
Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]

Example 2:

Input: "(00011)"
Output: ["(0.001, 1)", "(0, 0.011)"]
Explanation:
0.0, 00, 0001 or 00.01 are not allowed.

Example 3:

Input: "(0123)"
Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"]

Example 4:

Input: "(100)"
Output: ["(10, 0)"]
Explanation:
1.0 is not allowed.

Note:

  • ​4 <= S.length <= 12​​.
  • ​S[0] = "("​​​,​​S[S.length - 1] = ")"​​​, and the other elements in​​S​​ are digits.

题目描述

这道题不算难, 但需要考虑到很多特殊情形. 我是这样思考的, 对于一个字符串 ​​S​​​, 首先可以将它分为两个整数部分, 这一步骤可以看做是在 ​​S​​ 中插入逗号. 然后对于这两个整数字符串, 可以检查它们各自可以形成多少个有效的数字(包括整数和浮点数), 这里牵涉两个难点:

  • 如何形成有效的整数 ?
  • 如何形成有效的浮点数 ?

对于第一点, 需要考虑的情况有:

123 # 正常
012 # 0 开头, 属于特殊情况
000 # 全零 (也属于 0 开头这种特殊情况)
120 # 0 结尾

对于 ​​0​​ 开头这个特殊情况, 可以使用:

if (std::to_string(std::stoi(s)) != s)

来鉴别. 而对于第二点, 需要考虑的情况为:

123 # 正常, 在数字间任意位置插入小数点都能形成有效数字
012 # 0 开头但不是 0 结尾, 属于特殊情况, 只能在第一个 0 后面插入一个小数点
010 # 0 开头并且以 0 结尾, 属于特殊情况, 不能形成有效数字
000 # 和上一种情况一样, 0 开头并且以 0 结尾
120 # 0 结尾, 只能形成整数的结果, 不能形成浮点数

处理方法如下:

class Solution {
private:
vector<string> extend(const string &s) {
vector<string> res;
// 处理以 0 开头的情况
if (std::to_string(std::stoi(s)) != s) {
if (s.back() != '0') {
res.push_back(s.substr(0, 1) + "." + s.substr(1, s.size() - 1));
}
return res;
}
res.push_back(s); // 保留正常的整数结果
if (s.back() == '0') return res; // 以 0 结尾, 直接返回上一步得到的整数结果
// 正常情况, 加浮点数
for (int i = 0; i < s.size() - 1; ++ i) {
string decimal_num = s.substr(0, i + 1) + "." + s.substr(i + 1, s.size() - (i + 1));
res.push_back(decimal_num);
}
return res;
}
public:
vector<string> ambiguousCoordinates(string S) {
vector<string> res;
S = S.substr(1, S.size() - 2);
for (int i = 0; i < S.size() - 1; ++ i) {
auto first = S.substr(0, i + 1);
auto second = S.substr(i + 1, S.size() - (i + 1));
auto A = extend(first), B = extend(second);
for (auto &a : A)
for (auto &b : B)
res.push_back("(" + a + ", " + b + ")");
}
return res;
}
};