第3题根第2题很像,可能因为我选择是简单的题先开始的原因吧。
Palindrome number
我想法就是直接用第二题的解,然后拿过来做一个逻辑判断就可以了。只要是不等于reverse或者有负号,那就return false. 其他return true。
第四题 roman to int
因为罗马数字是一串字符,不知道如何把每个字符提取出来,所以看了别人的solution, 发现一个method可以用,叫*.toCharArray(), *就是任何string。这个method可以把 string里面的每个东西提取出来放到一个array里面。
The method toCharArray() returns an Array of chars after converting a String into sequence of characters. The returned array length is equal to the length of the String and the sequence of chars in Array matches the sequence of characters in the String.
我看的人基本上都是用了hashtable,然后从hashtable里面转换成数字,因为hashtable更节省时间吧。我觉得这个人的亮点就在于他对比了current和prev,如果current比prev大(通常不会),那就证明你要减去那个数字。这个方法很好,我一开始想法是用各种if and else if 来把所有情况概括,但是他直接用这个逻辑把答案轻松搞定了。
class Solution {
private static final Map<Character, Integer> map = new HashMap<Character, Integer>() {{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};
public int romanToInt(String s) {
if (s == null || s.length() == 0) return 0;
char[] values = s.toCharArray();
int result = map.get(values[0]);
for (int i = 1; i < values.length; i++) {
int prev = map.get(values[i - 1]);
int cur = map.get(values[i]);
if (cur > prev) {
result = result - prev + (cur - prev);
} else {
result = result + cur;
}
}
return result;
}
网友评论