回文
搞错了String类型的indexOf方法,理解成获取对应下标的值,实际上是在找对应值的下标。
4ms
耗时最少的方法尽量不会去调用jdk提供的方法,而是直接使用对应的数学逻辑关系来处理,
甚至用 == 代替equals方法。
罗马数字转整数
考虑到罗马数字开头出现每一种情况,然后截取该字符串开头
使用递归循环字符串判断开头。拉了一坨大的
class Solution13 {public static int romanToInt(String s) {Map<String,Integer> map = new HashMap<>();map.put("CD",400);map.put("CM",900);map.put("XL",40);map.put("XC",90);map.put("IV",4);map.put("IX",9);map.put("II",2);map.put("III",3);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);Integer count = 0;if (s.startsWith("III")){String substring = s.substring(0, 3);count += map.get(substring);s = s.substring(3);System.out.println(" s1= " + s);System.out.println(" count1= " + count);System.out.println( s.length() == 0);if (s.length() == 0)return count;} else if (s.startsWith("CD")||s.startsWith("CM") ||s.startsWith("XL") ||s.startsWith("XC") ||s.startsWith("IV") ||s.startsWith("IX")||s.startsWith("II")){String substring = s.substring(0, 2);count += map.get(substring);s = s.substring(2);System.out.println(" s2= " + s);System.out.println(" count2= " + count);System.out.println( s.length() == 0);if (s.length() == 0)return count;} else{count += map.get(s.substring(0,1));s = s.substring(1);System.out.println(" s3= " + s);System.out.println(" count3= " + count);System.out.println( s.length() == 0);if (s.length() == 0)return count;}return count + romanToInt(s);} }
2ms