3.Longest Substring Without Repeating Characters
案例google
滑动(保存无重复字符的)窗口, 窗口有left 和 当前遍历的脚标(勇往直前!)
若遇到一个以前遇见过的,比如第二个o 那么left就赋值为上一个o的脚标1。 同时用现在的脚标将o的脚标更新。 o->2 .
然后长度就是 当前 脚标-left
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int left = -1;
int result = 0;
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
left = Math.max(left, map.get(s.charAt(i)));
}
map.put(s.charAt(i), i);
result = Math.max(result, i - left);
}
return result;
}
13. Roman to Integer
class Solution {
public int romanToInt(String s) {
if (s == null || s.isEmpty()) { return -1; } char[] sChar = s.toCharArray(); Map<Character, 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); //用来记录位置 String sort = "IVXLCDM"; int sum = 0; for (int i = 0; i < sChar.length - 1; i++) { //如果当前字符与下个字符的位置相差2 则需要做两个字符的相减(先减 再加) if (map.get(sChar[i]) < map.get(sChar[i + 1]) && sort.indexOf(sChar[i + 1]) - sort.indexOf(sChar[i]) < 3) sum -= map.get(sChar[i]); else sum += map.get(sChar[i]); } return sum + map.get(sChar[sChar.length - 1]);
}
}