题解 | 字符串最后一个单词的长度

字符串最后一个单词的长度

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    while ((line = await readline())) {
        let theLength = 0;
		//因为要找到最后一个单词,也就是说要从后开始数。
        for (let index = line.length - 1; index >= 0; index--) {
			//如果是正常的大小字母,则长度加1。防止有些不是字母。
            if (/^[a-zA-Z]{1,1}$/.test(line[index])) {
                theLength = theLength + 1;
            }
			//theLength不为0,说明至少有一个字母了。并且是从后向前遍历,说明最后一个单词的首字母已经有了。
            if (!/^[a-zA-Z]{1,1}$/.test(line[index]) && theLength!==0) {
                console.log(theLength)
                break
            }
			//如果是不是大小字母,则长度重置为0,直到找到最后一个单词的最后一个字母。
            if (!/^[a-zA-Z]{1,1}$/.test(line[index])) {
                theLength = 0;
            }
			//如果角标为0,说明已经是输入的开始了,前面已经没有字母了,就直接输出长度。
            if (index===0) {
                console.log(theLength)
            }
        }
        
    }
})();

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务