Skip to content

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

题目描述

image-20220301103547452

示例

image-20220301103555801

代码

代码1 先转数组,取最后一位获取长度

js
/*
暴力解法
转换为数组
取最后一项
然后获取长度
*/

let readline = require('readline')
let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

rl.on('line', line=>{
    let arr = line.split(' ')
    let finalStr = arr[arr.length - 1]
    
    console.log(finalStr.length)
})

代码2 倒着找最后一位的空格,截取字符串

js
/*
倒着遍历,找到最后一个空格的索引
如果没有 索引就是0
如果有 就截取字符串
*/

let readline = require('readline')
let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

rl.on('line', line=>{
    let lastSpaceIndex = -1 // 默认空格的索引,倒着找,找到第一个就更新
    for( let i = line.length - 1; i >= 0; i-- ){
           if( line[i] === ' ' ){
               lastSpaceIndex = i
               break
           }
    }
    
    let finalStr = line.slice(lastSpaceIndex + 1)
    
    console.log(finalStr.length)
})

题目来源

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&tqId=21224&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37%26type%3D37%26page%3D1%26difficulty%3D2&difficulty=2&judgeStatus=undefined&tags=&title=