1. 程式人生 > >leetcode陣列或者字串常用方法總結

leetcode陣列或者字串常用方法總結

1.暴力法

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 List<String> restoreIpAddresses(String s) {
        List<String> res = new 
ArrayList<String>(); int len = s.length(); for(int i = 1; i<4 && i<len-2; i++){ for(int j = i+1; j<i+4 && j<len-1; j++){ for(int k = j+1; k<j+4 && k<len; k++){ String s1 = s.substring(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; } }
String操作中 subString不包括後面的

2.排序的思想在貪心演算法中還是很常見的

3.在陣列不需要排序時有需要o(n)複雜度時,就要找到題目的規律,考慮到左右兩邊的最大值或者最小值的思想有時有用。

此題的思路:對每一個位置的水面高度,需要同時考慮它左邊能承受的最大高度和右邊能承受的最大高度,再取min.

此題的思路: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).

4.關於陣列中連續子串的長度的問題

主要程式碼如下:

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. Only the first letter in this word is capital if it has more than one letter, like "Google".
解答:

publicboolean detectCapitalUse(Stringword) { returnword.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");}