Java String类知识总结并结合leetcode

22 篇文章 0 订阅
6 篇文章 0 订阅

字符串类型的转换

/* You convert primitive types to a string with toString
033
         * String byteString = Byte.toString(bigByte);
034
         * String shortString = Short.toString(bigByte);
035
         * String intString = Integer.toString(bigInt);
036
         * String longString = Long.toString(bigByte);
037
         * String floatString = Float.toString(bigByte);
038
         * String doubleString = Double.toString(bigByte);
039
         * String booleanString = Boolean.toString(bigByte);
040
         *
041
         * You convert from String to primitives with parse
042
         * int stringToInt = Integer.parseInt(intString);
043
         * parseShort, parseLong, parseByte, parseDouble,
044
         * parseBoolean, parseFloat
045
         */
http://www.newthinktank.com/2012/02/java-video-tutorial-13/
parse这个词的中文意思从语法或描述上分析


Compare Version Numbers

 

public class Solution {
    public int compareVersion(String version1, String version2) {
        //注意:string里可能包含多个小数点
        String[] v1 = version1.split("\\.");//正则表达式!!!
        String[] v2 = version2.split("\\.");
        int length = v1.length > v2.length ? v1.length : v2.length;
        int[] v1int = new int[length];
        int[] v2int = new int[length];
        int j = 0, k = 0, answer = 0, i = 0;
        //以长的字符串的长度作为比较长度,短的字符串后面补充0
        while(j < length)
        {
            if(j >= v1.length) v1int[j] = 0;
            else v1int[j] = Integer.parseInt(v1[j]);
            j++;
        }
         while(k < length)
        {
            if(k >= v2.length) v2int[k] = 0;
            else v2int[k] = Integer.parseInt(v2[k]);
            k++;
        }
        while(i < length)
        {
            if(v1int[i] > v2int[i]) 
            {
                answer = 1;
                break;
            }
            else if(v1int[i] < v2int[i])
            {
                answer = -1;
                break;
            }
            else
            {
                i++;
            }
        }
        return answer;
    }
}


Add Binary

 

public class Solution {
    public String addBinary(String a, String b) {
        //应该和加法器一样,有三个输入:a,b,carry_in
        //用到StringBuilder
        //可能要用到stack,因为结果我先算的低位的,但结果需要从高位到低位排列
        //本位结果的值由a,b,carry_in三个数值决定,三个均为1或者一个为1,则为1;其他情况为零
        //下一位的carry_in由a,b,carry_in三个数值决定,两个或两个以上为1,则carry_in为一
        int i = a.length() -1 , j= b.length() -1;//i和j的值作为charAt的index
        int carry_in = 0;
        Stack<String> temporaryanswer = new Stack<String>();
        StringBuilder answer = new StringBuilder();
        while( i >= 0 || j >= 0)
        //要注意从左往右读是我们平时阅读文字的习惯;但数学加法计算确实从右向左的
        {
            if(i >= 0 && j >= 0)
            {
                if(Integer.parseInt(String.valueOf(a.charAt(i)))+Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 3)
                //Integer.parseInt(String.valueOf(a.charAt(i))) Sting里的char转成int
                //charAt()索引范围为0~length()-1.
                {
                    temporaryanswer.push("1");
                    carry_in = 1;
                }
                else if(Integer.parseInt(String.valueOf(a.charAt(i)))+Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 2)
                {
                    temporaryanswer.push("0");
                    carry_in = 1;
                }
                else if(Integer.parseInt(String.valueOf(a.charAt(i)))+Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 1)
                {
                    temporaryanswer.push("1");
                    carry_in = 0;
                }
                else if(Integer.parseInt(String.valueOf(a.charAt(i)))+Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 0)
                {
                    temporaryanswer.push("0");
                    carry_in = 0;
                }
            }
            else if(i < 0 && j >= 0)
            {
                if(Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 2)
                {
                    temporaryanswer.push("0");
                    carry_in = 1;
                }
                else if(Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 1)
                {
                    temporaryanswer.push("1");
                    carry_in = 0;
                }
                else if(Integer.parseInt(String.valueOf(b.charAt(j)))+carry_in == 0)
                {
                    temporaryanswer.push("0");
                    carry_in = 0;
                }
            }
            else if(i >= 0 && j < 0)
            {
                if(Integer.parseInt(String.valueOf(a.charAt(i)))+carry_in == 2)
                {
                    temporaryanswer.push("0");
                    carry_in = 1;
                }
                else if(Integer.parseInt(String.valueOf(a.charAt(i)))+carry_in == 1)
                {
                    temporaryanswer.push("1");
                    carry_in = 0;
                }
                else if(Integer.parseInt(String.valueOf(a.charAt(i)))+carry_in == 0)
                {
                    temporaryanswer.push("0");
                    carry_in = 0;
                }
            }
            i--;
            j--;
        }
        if(carry_in == 1)temporaryanswer.push("1");
        while(!temporaryanswer.empty())
        {
            answer.append(temporaryanswer.pop());
        }
        String answer1 = answer.toString();//stringbuilder最后要转成string
        return answer1;
    }
}

Length of Last Word

<span style="font-size:14px;">public class Solution {
    public int lengthOfLastWord(String s) {
        //用split将字符串拆成字符串数组
        //If the last word does not exist, return 0.暂时理解为字符串为空。也有可能是字符串里包含其他非字母符号。想多了,原来有这么简单的题目,第一次一遍过,真是醉了
        String[] word = s.split(" ");//split空格
        if(word.length == 0) return 0;
        else return word[word.length -1].length();
    }
}</span>

Count and Say

 
public class Solution {
    public String countAndSay(int n) {
        //要用迭代
        //倒是可以建一个长度为n的String数组,来存每一个的结果
        StringBuilder[] answer = new StringBuilder[n];
        int i = 0, j = 0, count = 1;
        String say;
        for(i = 0; i < answer.length; i++)
        {  
            answer[i] = new StringBuilder();  
        } 
        answer[0].append("1");
        //Line 6: java.lang.NullPointerException
        //answer[0] = "1";
        //Line 6: error: incompatible types: String cannot be converted to StringBuilder
        i = 0;
        while(i < n-1)//因为第n个是通过n-1来计算的
        {
            say = String.valueOf(answer[i].charAt(j));//String里取出char再转String
            while(j < answer[i].length())
            {
                if(j == answer[i].length() - 1)//针对某个字符串倒数第一个字符的情况 
                {
                    answer[i+1].append(Integer.toString(count));
                    answer[i+1].append(say);
                }
                else if( Integer.parseInt(say) != Integer.parseInt(String.valueOf(answer[i].charAt(j+1))))//针对普通情况当前值和下一个值不相等的情况下
                //else if(say != String.valueOf(answer[i].charAt(j+1)))string间的比较不能用 ==
                //转成int作比较或者用equals
                //else if(!say.equals(String.valueOf(answer[i].charAt(j+1))))
                {
                    answer[i+1].append(Integer.toString(count));
                    answer[i+1].append(say);
                    say = String.valueOf(answer[i].charAt(j+1));//相比于上面一个情况,这里还要多加一步;把say改了
                    count = 1;//还要把count改成1 
                }
                else
                {
                    count++;
                }
                j++;
            }
            j = 0;
            i++;
            count =1;
        }
        String answerstring = answer[n-1].toString();
        return answerstring;
    }
}
//总结:1、StringBuilder数组(对象类的数组,在这样“StringBuilder[] answer = new StringBuilder[n];”的定义后,其实还不能使用,
//      for(i = 0; i < answer.length; i++)
//      {  
//          answer[i] = new StringBuilder();  
//      }
//      必须这样初始化
//      2、String.valueOf(answer[i].charAt(j));//String里取出char再转String的方法
//      3、对while循环里三种情况分类的理解

Valid Parentheses
public boolean isValid(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for(int i = 0; i < s.length(); ++i){
        char c = s.charAt(i);
        if(c == ')'){
            if(stack.isEmpty() || stack.pop() != '(')
                return false;
        } else if (c == ']'){
            if(stack.isEmpty() || stack.pop() != '[')
                return false;
        } else if (c == '}'){
            if(stack.isEmpty() || stack.pop() != '{')
                return false;
        } else
            stack.push(c);
    }
    return stack.isEmpty();
}

上面这个是leetcode上discuss部分别人的答案。
技术总结:
1、Deque的方法isEmpty()、pop()或者 removeFirst()、push()或者addFirst()也就是说这里Deque换成Stack也是一样的。
2、Deque<Character> deque = new ArrayDeque<Character>();必须要这么写(用ArrayDeque)
   Deque is an interface, and interfaces (and abstract classes) cannot be instantiated. You can declare a variable of type Deque and instantiate an ArrayDeque, the implementing class.
总结别人的思路:
1、遇到括号的前半部分存入queue,遇到括号的后半部分,就从queue里面pop出来看有没有与之对应的。 (再看看自己思路,真是感觉自己蠢到不行了)
2、

Implement strStr()

 
public class Solution {
    public int strStr(String haystack, String needle) {

    if(!haystack.contains(needle)) return -1;

    return haystack.indexOf(needle);
    }
}
上面这个是leetcode上discuss部分别人的答案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值