leetcode 字符串問題(一)

1、Count and Say
鏈接:https://leetcode.com/problems/count-and-say/
思路:注意一點,java中String類型改變耗時長,使用StringBuffer來代替String

public String countAndSay(int n) {
        if(n <= 0)
            return "";
        String s1 = "1";
        for(int i = 1; i < n; i++){
            StringBuffer temp = new StringBuffer();
            s1 += "@";
            int len = s1.length();
            int  count = 0;
            for(int j = 0; j < len; j++){
                if(j == 0)
                    count++;
                else{
                    if(s1.charAt(j) != s1.charAt(j - 1)){
                        temp.append(count);
                        temp.append(s1.charAt(j - 1));
                        count = 1;
                    }else count++;
                }
            }
            s1 = temp.toString();
        }
        return s1;
    }

2、Implement strStr()
鏈接:http://oj.leetcode.com/problems/implement-strstr/
思路:遍歷終止條件,減少遍歷次數;也可以使用KMP算法來求解

public int strStr(String haystack, String needle) {
        if(needle.isEmpty())
            return 0;
        int len1 = haystack.length(), len2 = needle.length();
        if(len1 < len2)
            return -1;
        for(int i = 0; i <= len1 - len2; i++){
            int j;
            for(j = 0; j < len2; j++){
                if(haystack.charAt(i + j ) != needle.charAt(j))
                    break;
            }
            if(j == len2)
                return i;
        }
        return  -1;
    }

KMP解法

public int strStr(String haystack, String needle) {
        if(haystack.equals(needle) || needle.length() < 1)
            return 0;
        int[] next = getNext(needle);
        int i=0,j=0;
        while(i < haystack.length() && j < needle.length()){
            if(haystack.charAt(i) == needle.charAt(j)){
                i++;
                j++;
            }else if(j==0){
                i++;
            }else{
                j = next[j];
            }
        }
        if(j>=needle.length())
            return i-j;
        return -1;
    }
    public static int[] getNext(String ps){
        char[] ss = ps.toCharArray();
        int len = ss.length;
        int[] next = new int[len+1];
        int  j = -1,  i = 0;
        next[0] = -1;
        while(i < len){
            if(j == -1 || ss[i] == ss[j]){
                i++;
                j++;
                next[i] = j;
            }else{
                j = next[j];
            }
        }
        return next;
    }

3、Group Anagrams
鏈接:http://oj.leetcode.com/problems/anagrams/
思路:將string按照字典序排序,存在hashmap中,如果錯位詞存在,則在list後面添加,如果不存在,則新增key,value對。注意將string轉化爲字符數組排序,然後根據字符數組新建string。

public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        List<List<String>> lists = new ArrayList<>();
        int len = strs.length;
        for(int i = 0; i < len; i++){
            char[] ch = strs[i].toCharArray();
            Arrays.sort(ch);
            String temp = new String(ch);
            if(map.containsKey(temp)){
                map.get(temp).add(strs[i]);
            }else {
                List<String> list1 = new ArrayList<>();
                list1.add(strs[i]);
                map.put(temp,list1);
            }
        }
        Iterator<Map.Entry<String,List<String>>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<String,List<String>> entry = iterator.next();
            List<String> temp_list = entry.getValue();
            Collections.sort(temp_list);
            lists.add(temp_list);
        }
        return lists;
    }

4、Text Justification
鏈接:https://leetcode.com/problems/text-justification/
思路:首先要做的就是確定每一行能放下的單詞數,即比較n個單詞的長度和加上n - 1個空格的長度跟給定的長度L來比較即可,找到了一行能放下的單詞個數,然後計算出這一行存在的空格的個數,是用給定的長度L減去這一行所有單詞的長度和。得到了空格的個數之後,就要在每個單詞後面插入這些空格,這裏有兩種情況,比如某一行有兩個單詞”to” 和 “a”,給定長度L爲6,如果這行不是最後一行,那麼應該輸出”to a”,如果是最後一行,則應該輸出 “to a “,所以這裏需要分情況討論,最後一行的處理方法和其他行之間略有不同。最後一個難點就是,如果一行有三個單詞,這時候中間有兩個空,如果空格數不是2的倍數,那麼左邊的空間裏要比右邊的空間裏多加入一個空格,那麼我們只需要用總的空格數除以空間個數,能除盡最好,說明能平均分配,除不盡的話就多加個空格放在左邊的空間裏,以此類推,

public List<String> fullJustify(String[] words, int maxWidth) {
        int len = words.length;
        List<String> list = new ArrayList<>();
        int i = 0;
        while(i < len) {
            int j = i;
            int temp_len = 0;
            while (j < len && (temp_len + words[j].length() + j - i) <= maxWidth) {
                temp_len += words[j++].length();
            }
            StringBuffer sb = new StringBuffer();
            int space = maxWidth - temp_len;
            for(int k = i; k < j; k++){
                sb.append(words[k]);
                if(space > 0){
                    int temp;
                    if(j == len){
                        if(j - k == 1) temp = space;
                        else temp = 1;
                    }else {
                        if(j - k - 1 > 0){
                            if (space % (j - k - 1) == 0) temp = space / (j - k - 1);
                            else temp = space / (j - k - 1) + 1;
                        }else temp = space;
                    }
                    int flag = temp;
                    while(flag > 0){
                        flag--;
                        sb.append(" ");
                    }
                    space -= temp;
                }
            }
            list.add(sb.toString());
            i = j;
        }
        return  list;
    }

5、Simplify Path
鏈接:https://leetcode.com/problems/simplify-path/
思路:將string切割存入字符串數組,使用棧保存路徑;最後將list數組加入路徑分隔符。

public String simplifyPath(String path) {
        String [] sb = path.split("/");
        Stack stack =  new Stack();
        for(String p : sb){
            if(!stack.isEmpty() && p.equals("..")){
                stack.pop();
            }else if(!p.equals("..") && !p.equals(".") && !p.equals("")){
                stack.push(p);
            }
        }
        List<String> list = new ArrayList(stack);
        return "/"+ String.join("/", list);
    }

6、Multiply Strings
鏈接:https://leetcode.com/problems/multiply-strings/
思路:兩個數,逐位相乘,放入數組,數組中的各個數,取餘保留在當前位置,取整加入下一位。

public String multiply(String num1, String num2) {
        int a = num1.length();
        int b = num2.length();
        int[] num3 = new int[a+b];
        int flag = 0;
        String s = "";
        int c = 0;
        int begin = 0;
        for(int i = 0; i < a; i++)
            for(int j = 0; j < b; j++){
                num3[j+i+1] += (num1.charAt(i) - '0') * (num2.charAt(j)- '0');
            }

        for(int i = num3.length - 1; i >= 0; i--){
            c = num3[i] + flag;
            flag = c / 10;
            num3[i] = c % 10;
        }

        while(begin < num3.length){
            if(num3[begin] != 0)
                break;
            begin++;
        }
        for(int j = begin; j < num3.length; j++){
            s += num3[j];
        }
        if(s == "")
            s = "0";
        return s;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章