LC 3
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
public class LengthOfLongestSubstring {
public int lengthOfLongestSubstring(String s) {
if (s.equals(null) || s.length() == 0)
return 0;
Map<Character, Integer> map = new HashMap<>();
int ans = 0;
for (int start = 0, end = 0; end < s.length(); end++) {
char alpha = s.charAt(end);
if (map.containsKey(alpha))
start = Math.max(map.get(alpha), start);
ans = Math.max(ans, end - start + 1);
map.put(s.charAt(end), end + 1);
}
return ans;
}
}
LC 13
罗马数字转整数
// 做法1:
class LC13 {
public static int romanToInt(String s) {
int n = s.length();
int roman_int = 0;
for(int i = 0; i < n; i++) {
switch(s.charAt(i)) {
case 'I':
roman_int = roman_int + 1;
break;
case 'V':
roman_int = roman_int + 5;
break;
case 'X':
roman_int = roman_int + 10;
break;
case 'L':
roman_int = roman_int + 50;
break;
case 'C':
roman_int = roman_int + 100;
break;
case 'D':
roman_int = roman_int + 500;
break;
case 'M':
roman_int = roman_int + 1000;
break;
default:
System.out.println("default");
break;
}
// 例外判断
if(i != 0) {
if(((s.charAt(i) == 'V') || (s.charAt(i) == 'X')) && (s.charAt(i - 1) == 'I'))
roman_int = roman_int - 1 * 2;
if(((s.charAt(i) == 'L') || (s.charAt(i) == 'C')) && (s.charAt(i - 1) == 'X'))
roman_int = roman_int - 10 * 2;
if(((s.charAt(i) == 'D')||(s.charAt(i) == 'M'))&&(s.charAt(i - 1) == 'C'))
roman_int = roman_int - 100 * 2;
}
}
return roman_int;
}
}
// 做法2:
class Solution {
Map<Character, Integer> symbolValues = 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) {
int ans = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
int value = symbolValues.get(s.charAt(i));
if (i < n - 1 && value < symbolValues.get(s.charAt(i + 1))) {
ans -= value;
} else {
ans += value;
}
}
return ans;
}
}