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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章