码迷,mamicode.com
首页 > 其他好文 > 详细

482. License Key Formatting - LeetCode

时间:2018-06-21 00:03:59      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:source   length   https   eve   href   ice   ble   数组   form   

Question

482.?License Key Formatting

技术分享图片

Solution

思路:字符串转化为char数组,从后遍历,如果是大写字母就转化为小写字母,如果是-就忽略,如果遍历了k个字符(排除-)就追加一个-

Java实现1:insert版(StringBuilder的append()与insert()效率比较)

public String licenseKeyFormatting(String S, int K) {
    StringBuilder sb = new StringBuilder();
    char[] arr = S.toCharArray();
    int count = 0;
    for (int i = arr.length - 1; i >= 0; i--) {
        char c = arr[i];
        if (c == '-') continue;
        if (count % K == 0) sb.insert(0, '-');
        if (c >= 'a' && c <= 'z') c -= 32;
        sb.insert(0, c);
        count++;
    }
    // return sb.substring(0, sb.length() - 1); // "---" 不通过
    return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
}

技术分享图片

Java实现2:append版

public String licenseKeyFormatting(String S, int K) {
    StringBuilder sb = new StringBuilder();
    // char[] arr = S.toCharArray();
    int count = 0;
    for (int i = S.length() - 1; i >= 0; i--) {
        char c = S.charAt(i);
        if (c == '-') continue;
        if (count % K == 0) sb.append('-');//sb.insert(0, '-');
        if (c >= 'a' && c <= 'z') c -= 32;
        sb.append(c);// sb.insert(0, c);
        count++;
    }
    // return sb.substring(0, sb.length() - 1); // "---" 不通过
    return sb.length() > 0 ? sb.reverse().substring(0, sb.length()-1) : "";
}

技术分享图片

482. License Key Formatting - LeetCode

标签:source   length   https   eve   href   ice   ble   数组   form   

原文地址:https://www.cnblogs.com/okokabcd/p/9206536.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!