【leetcode】2129.将标题首字母大写

97 阅读1分钟

leetcode-2129.png

题目简述:将给定的字符串里的单词按规则转换,单词长度小于等于2时,都转成小写,单词长度大于2时,首字母大写,其余小写。

这一题没什么难度,就是要记得ascii表里面大小写之差,这里的大小写之差不是26,而是32大写在前,小写在后

var capitalizeTitle = function (title) {
    let A = 'A'.charCodeAt(0)
    let Z = 'Z'.charCodeAt(0)
    let words = title.split(' ')
    let res = []
    for (let word of words) {
        if (word.length <= 2) {
            let tmp = ''
            for (let c of word) {
                let index = c.charCodeAt(0)
                if (index >= A && index <= Z) {
                    tmp += String.fromCharCode(index + 32)
                } else {
                    tmp += c
                }
            }
            res.push(tmp)
        } else {
            let first = word[0].charCodeAt(0)
            let tmp = ''
            if (first >= A && first <= Z) {
                tmp += word[0]
            } else {
                tmp += String.fromCharCode(first - 32)
            }
            for (let i = 1; i < word.length; ++i) {
                let c = word[i].charCodeAt(0)
                if (c >= A && c <= Z) {
                    tmp += String.fromCharCode(c + 32)
                } else {
                    tmp += word[i]
                }
            }
            res.push(tmp)
        }
    }
    return res.join(' ')
};

上面的代码就没有用api,直接纯手写转换,使用String.fromCharCode(num)将数字转成字符,使用c.charCodeAt(0)将字符转成数字。
下面这种解法就直接使用了toLowerCase()toUpperCase(),这样代码就会优雅很多了。

var capitalizeTitle = function(title) {
    let words = title.split(' ');
    let res = [];

    for (let word of words) {
        if (word.length <= 2) {
            res.push(word.toLowerCase());
        } else {
            let firstChar = word[0].toUpperCase();
            let restChars = word.slice(1).toLowerCase();
            res.push(firstChar + restChars);
        }
    }
    return res.join(' ');
};