String題目集合

---恢復內容開始-git

67. Add Binary正則表達式

Given two binary strings, return their sum (also a binary string).數組

For example,
a = "11"
b = "1"
Return "100".app

思路:這道題很差從後往前遍歷,仍是從前日後遍歷,但用個方法處理一下。此時應檢查是否還有另外一個字符串沒有被遍歷完。ui

若發現存在則繼續遍歷。遍歷完兩個字符串後,還需檢查進位是否爲 0,若進位不爲 0,還要加上進位。spa

public class AddBinary {
    public String addBinary(String a, String b) {
        if (a == null || b == null || a.length() == 0 || b.length() == 0)
            return null;
        int aLen = a.length();
        int bLen = b.length();
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        int i = 0;
        for (; i < aLen && i < bLen; i++) {
            int sum = (a.charAt(aLen - 1 - i) - '0') + (b.charAt(bLen - 1 - i) - '0') + carry;
            sb.insert(0, sum % 2);
            carry = sum / 2;
        }
        while (i < aLen) {
            int sum = (a.charAt(aLen - 1 - i) - '0') + carry;
            sb.insert(0, sum % 2);
            carry = sum / 2;
            i++;
        }
        while (i < bLen) {
            int sum = (b.charAt(bLen - 1 - i) - '0') + carry;
            sb.insert(0, sum % 2);
            carry = sum / 2;
            i++;
        }
        if (carry != 0)
            sb.insert(0, carry);
        return sb.toString();
    }
}

293.Flip Game3d

You are playing the following Flip Game with your friend: Given a string that contains only these two characters:+ and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.指針

Write a function to compute all possible states of the string after one valid move.code

For example, given s = "++++", after one move, it may become one of the following states:blog

[

  "--++",

  "+--+",

  "++--"

]

If there is no valid move, return an empty list [].

思路:該題不難,判斷有沒有連續的兩個++號便可。

public List<String> generatePossibleNextMoves(String s) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < s.length() - 1; i++) {
            if (s.charAt(i) == '+' && s.charAt(i + 1) == '+') {
                list.add(s.substring(0, i) + "--" + s.substring(i + 2));
            }
        }
        return list;
    }
}

408. Valid Word Abbreviation

Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

A string such as 「word」 contains only the following valid abbreviations:

[「word」, 「1ord」, 「w1rd」, 「wo1d」, 「wor1」, 「2rd」, 「w2d」, 「wo2」, 「1o1d」, 「1or1」, 「w1r1」, 「1o2」, 「2r1」, 「3d」, 「w3」, 「4」] 

Notice that only the above abbreviations are valid abbreviations of the string 「word」. Any other string is not a valid abbreviation of 「word」.

Note: 

Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

思路:咱們使用雙指針分別指向兩個單詞的開頭,循環的條件是兩個指針都沒有到各自的末尾,

若是指向縮寫單詞的指針指的是一個數字的話,若是當前數字是0,返回false,由於數字不能以0開頭,

而後咱們要把該數字總體取出來,因此咱們用一個while循環將數字總體取出來,

而後指向原單詞的指針也要對應的向後移動這麼多位數。若是指向縮寫單詞的指針指的是一個字母的話,

那麼咱們只要比兩個指針指向的字母是否相同,不一樣則返回false,相同則兩個指針均向後移動一位,參見代碼以下:

public class ValidWordAbbreviation {
    public boolean validWordAbbreviation(String word, String abbr) {
        int i = 0, j = 0, start = -1;

        while (i < word.length() && j < abbr.length()) {
            if (Character.isDigit(abbr.charAt(j))) {
                if (start == -1) {
                    start = j;
                    if (abbr.charAt(j) - '0' == 0) {
                        return false;
                    }
                }
                if (j == abbr.length() - 1) {

                    int num = Integer.parseInt(abbr.substring(start, j + 1));
                    i += num;
                }
                j++;
            } else {
                if (start != -1) {

                    int num = Integer.parseInt(abbr.substring(start, j));
                    i += num;
                    start = -1;
                } else {
                    if (word.charAt(i) == abbr.charAt(j)) {
                        i++;
                        j++;
                    } else {
                        return false;
                    }
                }
            }
        }
        if (i == word.length() && j == abbr.length())
            return true;
        else
            return false;
    }
}

383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false

canConstruct("aa", "ab") -> false

canConstruct("aa", "aab") -> true

思路:利用hashmap去存儲magazine中的字符,每次出現相同的字符就加1,而後去遍歷ransom中的,出現一次相同的就減1,

直到爲負值,或者ransom出現了magazine中沒有存儲過的值。

public class RansomNote {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < magazine.length(); i++) {
            if (map.containsKey(magazine.charAt(i))) {
                map.put(magazine.charAt(i), map.get(magazine.charAt(i)) + 1);
            } else {
                map.put(magazine.charAt(i), 1);
            }
        }

        for (int i = 0; i < ransomNote.length(); i++) {
            if (map.containsKey(ransomNote.charAt(i))) {
                int temp = map.get(ransomNote.charAt(i));
                temp--;
                if (temp < 0) {
                    return false;
                }
                map.put(ransomNote.charAt(i), temp);
            } else {
                return false;
            }
        }
        return true;
    }
}

345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".

public class Solution {
    public String reverseVowels(String s) {
        int left=0;
        int right=s.length()-1;
        char[] a=s.toCharArray();
        String vowels = "aeiouAEIOU";
        while(left<right) {
            while(left<right && !vowels.contains(a[left]+"")) {
                left++;
            }
            while(left<right && !vowels.contains(a[right]+"")) {
                right--;
            }
            if(left<right) {
                char temp=s.charAt(left);
                a[left]=a[right];
                a[right]=temp;
            }
            left++;
            right--;
        }
        return new String(a);
    }
}

 344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

public class Solution {
    public String reverseString(String s) {
        int left=0;
        int right=s.length()-1;
        char[] c=s.toCharArray();
        while(left<right) {
            char temp=c[right];
            c[right]=c[left];
            c[left]=temp;;
            left++;
            right--;
        }
        return new String(c);
    }
}

13. Roman to Integer 

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

思路:要求把羅馬數字轉換爲整數。倒序從右判斷,重點判斷4,40,和400的狀況處理。

public class Solution {
    public int romanToInt(String s) {
        int res = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            switch (c) {
                case 'I':
                    res += (res >= 5 ? -1 : 1);
                    break;
                case 'V':
                    res += 5;
                    break;
                case 'X':
                    res += 10 * (res >= 50 ? -1 : 1);
                    break;
                case 'L':
                    res += 50;
                    break;
                case 'C':
                    res += 100 * (res >= 500 ? -1 : 1);
                    break;
                case 'D':
                    res += 500;
                    break;
                case 'M':
                    res += 1000;
                    break;
                }
        }
    return res;
    }
}

12. Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

public class IntegertoRoman {
    public String intToRoman(int num) {
        int n[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String r[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        String s = "";
         for(int i = 0; num > 0; num %= n[i], ++ i) {
             for(int j = 0, k = num / n[i]; j < k; ++ j) {
                 s += r[i]; 
             }
         }
         return s;   
    }
}

 

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

思路:找到字符串數組的最長的公共前綴,利用個下標比較或者利用indexof,這裏提供indexof的寫法。

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0) {
            return "";
        }
        for(int i=0;i<strs.length;i++) {
            while(strs[i].indexOf(strs[0])!=0) {
                strs[0]=strs[0].substring(0,strs[0].length()-1);
            }
        }
        return strs[0];
    }
}

434. Number of Segments in a String   

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"

Output: 5

思路:其實這個題就是檢測空白的地方。有兩種思路,第一種先用trim處理頭尾的空格。而後用split("\\s+")去處理中間的空白部分

補充一下:String[] split(String regex)根據給定的正則表達式的匹配來拆分此字符串。 \\s表示空格,回車,換行等空白符 

+ 表示一個或者多個的意思。split("\\s+") 按空格,製表符,等進行拆分(也就是說它是按空白部分進行拆分,

無論這個空白使用什麼操做留下的,提如空格鍵 tab鍵

而split(" +") 按空格進行拆分(也就是說只有按空格鍵流出來的空白纔會是拆分的一句

此處提供兩種思路

public int countSegments(String s) {
        int cnt = 0;
        int i = 0;
        for (i = 0; i < s.length(); i++) {
            if (i == 0 && s.charAt(i) != ' ') {
                cnt++;//若是第一個值不爲空
            }
            if (i > 0 && s.charAt(i - 1) == ' ' && s.charAt(i) != ' ') {
                cnt++;// 若是當前不是空格,而前一個是空格,+1
            }

        }
        return cnt;
    }
public int countSegmentsII(String s) {
        s=s.trim();
        if(s.length()==0){
            return 0;
        }
        return s.split("\\s+").length;
    }

 

459. Repeated Substring Pattern 

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

Example 3:

Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

思路:自字符串必定可以被整除,咱們從這點出發,從兩個子字符串開始查找,注意後面比較的時候能夠不用stringbuffer,

能夠利用一個for循環來比較後幾段是否同樣。

public class RepeatedSubstringPattern {
    public boolean repeatedSubstringPattern(String str) {
        for (int i = str.length() / 2; i >= 1; i--) {
            if (str.length() % i == 0) {
                String substr = str.substring(0, i);
                int size = str.length() / i;
                int j;
                for (j = 1; j < size; j++) {// 巧妙避開stringbuffer,若是不知足條件就跳出循環,
                                            // 繼續尋找新的自字符串長度,若是最後知足,那麼必定符合下面
                                            // j==size那個條件,但注意j要放在外面定義,要不是局部變量
                    if (!substr.equals(str.substring(i * j, i + i * j))) {
                        break;
                    }
                }
                if (j == size) {
                    return true;
                }
            }
        }
        return false;
    }
}

20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

思路:典型的用棧的題,先用hashmap將字符處理一下,而後尋找便可,最後要注意查看棧是否爲空

public class ValidParentheses {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (map.keySet().contains(s.charAt(i))) {
                stack.push(s.charAt(i));
            } else {
                if (!stack.isEmpty() && s.charAt(i) == map.get(stack.peek())) {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

28. Implement strStr()  

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

思路:這道題給了咱們兩個字符串,haystack和needle,讓咱們判斷needle是不是haystack的子字符串,若是是,返回起始的索引位置

若是不是,返回-1.起始這道題利用indexof直接解決,但估計是想讓咱們變相實現下indexof,因此這裏兩種解法都寫一下。

public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
public class Solution {
    public int strStr(String haystack, String needle) {
        for(int i=0;;i++) {
            for(int j=0;;j++) {
                if(j==needle.length()) {
                    return i;
                }
                if(j+i==haystack.length()) {
                    return -1;
                }
                if(haystack.charAt(i+j)!=needle.charAt(j)) {
                    break;
                }
            }
        }
    }
}

157.Read N Characters Given Read4 

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note: The read function will only be called once for each test case.

思路:用一個臨時數組,存放每次read4讀到字符,再用一個指針標記buf數組目前存儲到的位置,而後將這個臨時數組的內容存到buf相應的位置就好了。

這裏須要注意兩個corner case:1.若是本次讀到多個字符,可是咱們只須要其中一部分就能完成讀取任務時,咱們要拷貝的長度是本次讀到的個數和剩餘所需個數中較小的

2.若是read4沒有讀滿4個,說明數據已經讀完,這時候對於讀到的數據長度,由於也可能存在咱們只須要其中一部分的狀況,因此要返回總所需長度和目前已經讀到的長度的較小

public class ReadNCharactersGivenReadFour extends Reader4{
    public int read(char[] buf, int n) {
        for(int i=0;i<n;i+=4) {
            char[] temp=new char[4];
            int length=read4(temp);
              // 將臨時數組拷貝至buf數組,這裏拷貝的長度是本次讀到的個數和剩餘所需個數中較小的
            System.arraycopy(temp, i, buf, i, Math.min(length, n-i));
             // 若是讀不滿4個,說明已經讀完了,返回總所需長度和目前已經讀到的長度的較小的
            if(length<4) {
                return Math.min(i+length, n);
            }
        }
        // 若是循環內沒有返回,說明讀取的字符是4的倍數
        return n;
    }
}

158.Read N Characters Given Read4 II - Call multiple times

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note: The read function may be called multiple times.

思路:由於要調用屢次,這裏又多了一些corner case:

第一次調用時,若是read4讀出的多餘字符咱們要先將其暫存起來,這樣第二次調用時先讀取這些暫存的字符

第二次調用時,若是連暫存字符都沒讀完,那麼這些暫存字符還得留給第三次調用時使用

因此,難點就在於怎麼處理這個暫存字符。由於用數組和指針控制對第二種狀況比較麻煩,且這些字符知足先進先出,因此咱們能夠用一個隊列暫存這些字符。這樣,只要隊列不爲空,就先讀取隊列。

public class ReadNCharactersGivenRead4II extends Reader4{
     Queue<Character> remain = new LinkedList<Character>();
        public int read(char[] buf, int n) {
            int i = 0;
            // 隊列不爲空時,先讀取隊列中的暫存字符
            while(i < n && !remain.isEmpty()){
                buf[i] = remain.poll();
                i++;
            }
            for(; i < n; i += 4){
                char[] tmp = new char[4];
                int len = read4(tmp);
                // 若是讀到字符多於咱們須要的字符,須要暫存這些多餘字符
                if(len > n - i){
                    System.arraycopy(tmp, 0, buf, i, n - i);
                    // 把多餘的字符存入隊列中
                    for(int j = n - i; j < len; j++){
                        remain.offer(tmp[j]);
                    }
                // 若是讀到的字符少於咱們須要的字符,直接拷貝
                } else {
                    System.arraycopy(tmp, 0, buf, i, len);
                }
                // 一樣的,若是讀不滿4個,說明數據已經讀完,返回總所需長度和目前已經讀到的長度的較小的
                if(len < 4) return Math.min(i + len, n);
            }
            // 若是到這裏,說明都是完美讀取,直接返回n
            return n;
        }
}
相關文章
相關標籤/搜索