10. 字符串

10. 字符串

单纯考String的问题主要考一些基本操作,比如:

  • How to split String into a String array?

    • LC165. compare version numbers

  • How to get indexOf()

  • How to convert String into int?

    • Integer.parseInt()

繁琐的字符串处理

  • check sign

  • Long type

public String fractionToDecimal(int numerator, int denominator) {
        //handle exception
        if(denominator == 0) return "NaN";
        if(numerator == 0) return "0";

        //build a StringBuilder
        StringBuilder sb = new StringBuilder();

        //check the sign
        Long n = new Long(numerator);
        Long d = new Long(denominator);
        if(n * d < 0){
            sb.append("-");
        }
        //make n and d all positive
        n = Math.abs(n);
        d = Math.abs(d);

        //get the divide result
        sb.append(n/d);
        //if no remainder, return 
        if(n % d == 0){
            return sb.toString();
        }

        sb.append(".");
        long r = n % d;
        Map<Long, Integer> map = new HashMap<>();//key is the remainder, value is the index of this remainder in StringBuilder

        while(r > 0){
            if(map.containsKey(r)){
                sb.insert(map.get(r), "(");
                sb.append(")");
                break;
            }else{
                map.put(r, sb.length());//put into hashmap first
                r *= 10;
                sb.append(r / d);

                r %= d;
            }
        }
        return sb.toString();
    }

Validate IP address

  • 巨多edge case, 全文背诵吧

  • 这题还有个小技巧:IP.split("\:", -1)

Detect Capital

  • 这题放进来纯粹是为了对比自己写的code和别人的clean code的差距

  • 主要还是solution不同

Last updated

Was this helpful?