leetcode 解题

leetcode网址

罗马数字转整数

Description

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
public int romanToInt(String s) {
HashMap<String, Integer> map = new HashMap<>();
map.put("I", 1);
map.put("V", 5);
map.put("X", 10);
map.put("L", 50);
map.put("C", 100);
map.put("D", 500);
map.put("M", 1000);

if (s.length() == 1)
return map.get(String.valueOf(s.charAt(0)));
int sum = 0;
int temp = map.get(String.valueOf(s.charAt(0)));
int next = 0;
int pre = 0;
for (int i = 0; i < s.length() - 1; i++) {
next = map.get(String.valueOf(s.charAt(i + 1)));
pre = map.get(String.valueOf(s.charAt(i)));
if (next > pre) {
temp = next - temp;
} else if (next == pre) {
temp = next + temp;
} else {
sum = sum + temp;
temp = next;
}
}

return sum + temp;
}

有效的括号

Description

栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public boolean isValid(String s) {
if (s.equals("")) return true;
if (s.isEmpty() || s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
char[] chars = s.toCharArray();
for (char c : chars) {
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else {
if (stack.isEmpty()) return false;
if (c == '}' && !stack.pop().equals('{')) return false;
if (c == ']' && !stack.pop().equals('[')) return false;
if (c == ')' && !stack.pop().equals('(')) return false;
}

}
return stack.isEmpty();
}

合并两个有序链表

Description

递归处理

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;

if (l2 == null) return l1;

ListNode listNode;

if (l1.val < l2.val) {
listNode = l1;
listNode.next = mergeTwoLists(l1.next, l2);
} else {
listNode = l2;
listNode.next = mergeTwoLists(l1, l2.next);
}
return listNode;
}
Wangsz wechat
关注公众号,一起做happy wind man~~~