class Solution { public boolean wordBreak(String s, List<String> wordDict) { int n = s.length(); int max_length=0; for(String temp:wordDict){ max_length = temp.length() > max_length ? temp.length() : max_length; } // memo[i] 表示 s 中以 i - 1 结尾的字符串是否可被 wordDict 拆分 boolean[] memo = new boolean[n + 1]; memo[0] = true; for (int i = 1; i <= n; i++) { for (int j = i-1; j >= 0 && max_length >= i - j; j--) { if (memo[j] && wordDict.contains(s.substring(j, i))) { memo[i] = true; break; } } } return memo[n]; } }
344 反转字符串
从两头往中间走
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution { public: string reverseString(string s) { int i = 0, j = s.size() - 1; while (i < j){ swap(s[i],s[j]); i++; j--; } return s; } };
字符串转换为整数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class Solution { public int StrToInt(String str) { if (str == null || str.length() == 0) return 0; boolean isNegative = str.charAt(0) == '-'; int ret = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (i == 0 && (c == '+' || c == '-')) /* 符号判定 */ continue; if (c < '0' || c > '9') /* 非法输入 */ return 0; ret = ret * 10 + (c - '0'); } return isNegative ? -ret : ret; } }