LeetCode 补充题 13. 中文数字转阿拉伯数字
题目描述
思路分析
解法一:分段累加(推荐)
核心思路:
- 用
num记录当前数字,section记录万以内的累加,result记录总和。- 遇到
十/百/千时,若num为 0 说明省略了“一”,默认用 1;再累加到section。- 遇到
万/亿时,将section + num乘以单位并累加到result,然后清空section。
复杂度分析:
- 时间复杂度:O(n),其中 n 表示字符串长度。
- 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
public int chineseToNumber(String s) {
Map<Character, Integer> digit = new HashMap<>();
digit.put('零', 0);
digit.put('一', 1);
digit.put('二', 2);
digit.put('两', 2);
digit.put('三', 3);
digit.put('四', 4);
digit.put('五', 5);
digit.put('六', 6);
digit.put('七', 7);
digit.put('八', 8);
digit.put('九', 9);
Map<Character, Integer> unit = new HashMap<>();
unit.put('十', 10);
unit.put('百', 100);
unit.put('千', 1000);
unit.put('万', 10000);
unit.put('亿', 100000000);
int num = 0;
int section = 0;
int result = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (digit.containsKey(c)) {
num = digit.get(c);
continue;
}
int u = unit.get(c);
if (u < 10000) {
// 十百千,按万内累加
if (num == 0) {
num = 1;
}
section += num * u;
} else {
// 万亿,完成一个分段
section = (section + num) * u;
result += section;
section = 0;
}
num = 0;
}
return result + section + num;
}
}
func chineseToNumber(s string) int {
digit := map[rune]int{
'零': 0, '一': 1, '二': 2, '两': 2, '三': 3,
'四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9,
}
unit := map[rune]int{
'十': 10, '百': 100, '千': 1000, '万': 10000, '亿': 100000000,
}
num := 0
section := 0
result := 0
for _, c := range s {
if v, ok := digit[c]; ok {
num = v
continue
}
u := unit[c]
if u < 10000 {
// 十百千,按万内累加
if num == 0 {
num = 1
}
section += num * u
} else {
// 万亿,完成一个分段
section = (section + num) * u
result += section
section = 0
}
num = 0
}
return result + section + num
}
相似题目
| 题目 | 难度 | 考察点 |
|---|---|---|
| 273. 整数转换英文表示 | 困难 | 字符串、分段处理 |
| 12. 整数转罗马数字 | 中等 | 字符串、数值映射 |
| 13. 罗马数字转整数 | 简单 | 字符串、数值映射 |
| 8. 字符串转换整数 (atoi) | 中等 | 字符串解析 |
| 65. 有效数字 | 困难 | 字符串解析 |
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议,转载请注明出处!