1694. 重新格式化电话号码

1694. 重新格式化电话号码
1694. 重新格式化电话号码_第1张图片


Java:while 切糖果

class Solution {
    public String reformatNumber(String number) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < number.length(); ++i) {
            char ch = number.charAt(i);
            if (Character.isDigit(ch)) {
                sb.append(ch);
            }
        }

        int n = sb.length();
        int pt = 0;
        StringBuilder ans = new StringBuilder();
        while (n > 0) {
            if (n > 4) {
                ans.append(sb.substring(pt, pt + 3) + "-");
                pt += 3;
                n -= 3;  // 一个步长一个步长的减小
            } else {
                if (n == 4) {
                    ans.append(sb.substring(pt, pt + 2) + "-" + sb.substring(pt + 2, pt + 4));
                } else {
                    ans.append(sb.substring(pt, pt + n));
                }
                break;
            }
        }
        return ans.toString();
    }
}

Java:自己搓的代码

class Solution {
    public String reformatNumber(String number) {
        String s1 = number.replace("-", "");
        String s2 = s1.replace(" ", "");
        System.out.println(s2);
        int n = s2.length();
        int m = n % 3;
        int size = 0;
        if (m == 0) {
            size = n;
        } else if (m == 1) {
            size = n - 4;
        } else {
            size = n - 2;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(s2.charAt(i));
            if ((i != size-1) && (i+1) % 3 == 0) {
                sb.append("-");
            }
        }
        if (m == 1) {
            sb.append("-");
            sb.append(s2.charAt(n - 4));
            sb.append(s2.charAt(n - 3));
            sb.append("-");
            sb.append(s2.charAt(n - 2));
            sb.append(s2.charAt(n - 1));
        } else if (m == 2) {
            sb.append("-");
            sb.append(s2.charAt(n - 2));
            sb.append(s2.charAt(n - 1));
        }
        if (sb.toString().startsWith("-")) {
            return sb.toString().substring(1);
        }
        return sb.toString();
    }
}

你可能感兴趣的:(LeetCode刷题,算法)