Skip to content

Commit 01a4ab8

Browse files
committed
string O(n) O(1)
1 parent 94c2f58 commit 01a4ab8

File tree

1 file changed

+74
-36
lines changed

1 file changed

+74
-36
lines changed

leetcode-13-RomanToInteger.js

Lines changed: 74 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,3 @@
1-
/**
2-
* @param {string} s
3-
* @return {number}
4-
*/
5-
6-
// p: string;
7-
// r: int;
8-
9-
// i
10-
// MCMXCIVX
11-
// j
121
const regular = {
132
I: 1,
143
V: 5,
@@ -19,35 +8,84 @@ const regular = {
198
M: 1000,
209
};
2110

22-
const special = {
23-
IV: 4,
24-
IX: 9,
25-
XL: 40,
26-
XC: 90,
27-
CD: 400,
28-
CM: 900,
29-
};
30-
3111
var romanToInt = function (s) {
32-
let i = 0,
33-
j = 1;
34-
let count = 0;
35-
while (i < s.length) {
36-
if (s[i] + s[j] in special) {
37-
console.log(s[i] + s[j]);
38-
count += special[s[i] + s[j]];
39-
i += 2;
40-
j += 2;
12+
let total = 0;
13+
for (let i = 0; i < s.length; i++) {
14+
if (regular[s[i]] < regular[s[i + 1]]) {
15+
total -= regular[s[i]];
4116
} else {
42-
count += regular[s[i]];
43-
i++;
44-
j++;
17+
total += regular[s[i]];
4518
}
4619
}
4720

48-
return count;
21+
return total;
4922
};
5023

51-
// console.log(romanToInt("III"));
52-
// console.log(romanToInt("LVIII"));
53-
console.log(romanToInt("MCMXCIV"));
24+
// const special = {
25+
// IV: 4,
26+
// IX: 9,
27+
// XL: 40,
28+
// XC: 90,
29+
// CD: 400,
30+
// CM: 900,
31+
// };
32+
33+
// var romanToInt = function(s) {
34+
// let total = 0;
35+
// let i = 0;
36+
// while (i < s.length) {
37+
// const temp = s[i] + s[i + 1];
38+
// if (temp in special) {
39+
// total += special[temp];
40+
// i += 2;
41+
// } else {
42+
// total += regular[s[i]]
43+
// i++;
44+
// }
45+
// }
46+
// return total;
47+
// };
48+
49+
// TRASH vvvvv
50+
// const regular = {
51+
// I: 1,
52+
// V: 5,
53+
// X: 10,
54+
// L: 50,
55+
// C: 100,
56+
// D: 500,
57+
// M: 1000,
58+
// };
59+
60+
// const special = {
61+
// IV: 4,
62+
// IX: 9,
63+
// XL: 40,
64+
// XC: 90,
65+
// CD: 400,
66+
// CM: 900,
67+
// };
68+
69+
// var romanToInt = function (s) {
70+
// let i = 0,
71+
// j = 1;
72+
// let count = 0;
73+
// while (i < s.length) {
74+
// if (s[i] + s[j] in special) {
75+
// console.log(s[i] + s[j]);
76+
// count += special[s[i] + s[j]];
77+
// i += 2;
78+
// j += 2;
79+
// } else {
80+
// count += regular[s[i]];
81+
// i++;
82+
// j++;
83+
// }
84+
// }
85+
86+
// return count;
87+
// };
88+
89+
// // console.log(romanToInt("III"));
90+
// // console.log(romanToInt("LVIII"));
91+
// console.log(romanToInt("MCMXCIV"));

0 commit comments

Comments
 (0)