File tree Expand file tree Collapse file tree 2 files changed +24
-23
lines changed
src/main/java/com/fibers/algorithm/leetcode Expand file tree Collapse file tree 2 files changed +24
-23
lines changed Original file line number Diff line number Diff line change 1
1
package com .fibers .algorithm .leetcode ._013 ;
2
2
3
- import java .util .LinkedHashMap ;
3
+ import java .util .HashMap ;
4
4
import java .util .Map ;
5
5
6
6
public class Solution {
@@ -11,36 +11,37 @@ public static void main(String[] args) {
11
11
}
12
12
13
13
public int romanToInt (String s ) {
14
- int result = 0 ;
15
- Map <String , Integer > map = new LinkedHashMap < String , Integer >() {
14
+
15
+ Map <Character , Integer > map = new HashMap < Character , Integer >() {
16
16
{
17
- put ("M" , 1000 );
18
- put ("CM" , 900 );
19
- put ("D" , 500 );
20
- put ("CD" , 400 );
21
- put ("C" , 100 );
22
- put ("XC" , 90 );
23
- put ("L" , 50 );
24
- put ("XL" , 40 );
25
- put ("X" , 10 );
26
- put ("IX" , 9 );
27
- put ("V" , 5 );
28
- put ("IV" , 4 );
29
- put ("I" , 1 );
17
+ put ('M' , 1000 );
18
+ put ('D' , 500 );
19
+ put ('C' , 100 );
20
+ put ('L' , 50 );
21
+ put ('X' , 10 );
22
+ put ('V' , 5 );
23
+ put ('I' , 1 );
30
24
}
31
25
};
32
26
33
27
if (s == null || s .length () == 0 ) {
34
28
return 0 ;
35
29
}
36
30
37
- while (s .length () != 0 ) {
38
- for (String key : map .keySet ()) {
39
- if (s .startsWith (key )) {
40
- result += map .get (key );
41
- s = s .substring (key .length ());
42
- break ;
31
+ int result = 0 ;
32
+ char [] charArray = s .toCharArray ();
33
+ for (int i = 0 ; i < charArray .length ; i ++) {
34
+ Integer current = map .get (charArray [i ]);
35
+ if (i < charArray .length - 1 ) {
36
+ Integer next = map .get (charArray [i + 1 ]);
37
+
38
+ if (current >= next ) {
39
+ result += current ;
40
+ } else {
41
+ result -= current ;
43
42
}
43
+ } else {
44
+ result += current ;
44
45
}
45
46
}
46
47
Original file line number Diff line number Diff line change @@ -30,6 +30,6 @@ public void rotate(int[] nums, int k) {
30
30
int temp = nums [i ];
31
31
nums [i ] = nums [len + k - i - 1 ];
32
32
nums [len + k - i - 1 ] = temp ;
33
- }ByteBuffer
33
+ }
34
34
}
35
35
}
You can’t perform that action at this time.
0 commit comments