Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
public class Solution { public ListString操作中 subString不包括后面的restoreIpAddresses(String s) { List res = new ArrayList (); int len = s.length(); for(int i = 1; i<4 && i 2; i++){ for(int j = i+1; j4 && j 1; j++){ for(int k = j+1; k 4 && k 0,i), s2 = s.substring(i,j), s3 = s.substring(j,k), s4 = s.substring(k,len); if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)){ res.add(s1+"."+s2+"."+s3+"."+s4); } } } } return res; } public boolean isValid(String s){ if(s.length()>3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s)>255) return false; return true; } }
比如:leetcode 42.Trapping Rain Water(数组注水量多少)
此题的思路:对每一个位置的水面高度,需要同时考虑它左边能承受的最大高度和右边能承受的最大高度,再取min.
再比如:Longest Consecutive Sequence
此题的思路:We will use HashMap. The key thing is to keep track of(记录) the sequence length and store that in the boundary(边界) points of the sequence. For example, as a result, for sequence {1, 2, 3, 4, 5}, map.get(1) and map.get(5) should both return 5.因为下一次肯能有连接的时候只会和边界的值进行连接,所以能够达到准确记录sequence的长度问题。达到复杂度是o(n).
参考:Longest Consecutive Sequence和First_Missing_Positive都有用到
主要代码如下:
for (int i = 0; i < k; i++) { if (!map.containsKey(m[i])) { int left = map.containsKey(m[i] - 1) ? map.get(m[i] - 1) : 0; int right = map.containsKey(m[i] + 1) ? map.get(m[i] + 1) : 0; int sum = left + right + 1; map.put(m[i], sum); map.put(m[i] - left, sum); map.put(m[i] + right, sum); } else { continue; } }
5.正则表达式的使用
第一题:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.
解答:此题字符串中可能有标点符号或者空格,所以需要先清洗字符串,使用到正则表达式。replaceAll的第一个参数可以是正则表达式
public boolean isPalindrome(String s) {
String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
String rev = new StringBuffer(actual).reverse().toString();
return actual.equals(rev);
}
第二题:
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
public boolean detectCapitalUse(String word) { return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");}