如题,给出一个字符串,里面包含若干单词,单词之间用空格分隔。找出字符串中长度最长的单词。
function findTheLongestWord(inputStr:string){
    if(inputStr === undefined || inputStr.trim() === ""){
        return ""
    }
    inputStr = inputStr.trim();
    console.log(`输入:${inputStr}`);
    
    let strLength = inputStr.length;
    //当前遍历指针位置
    let position = 0;
    //开始记录单词长度的标志位
    let startFlag = false;
    //单词开始的位置
    let wordStartPos = 0;
    //单词结束的位置
    let wordEndPos = wordStartPos;
    //最长单词长度
    let maxWordLength = 0;
    //最长单词
    let maxWord = "";

    while(position < strLength){
        let currentChar = inputStr.charAt(position);
        // 出现第一个不为空的字符时,同时没有开始记录单词长度,就立即开始记录。
        if(currentChar !== " "){
            if(!startFlag){
                startFlag = true;
                wordStartPos = position;
            }else{
                wordEndPos = position;
            }
        }
        // 出现空格就判断一下。特殊情况:字符串最后一个单词后面已经没有空格了
        if(currentChar === " " || position === strLength - 1){
            // 如果已经处于记录长度的状态,就开始长度判断
            let currentWordLength = 0;
            if(startFlag){
                wordEndPos = position;
                if(position === strLength - 1){
                    wordEndPos++;
                }
                startFlag = false;
                currentWordLength = wordEndPos - wordStartPos;
                if(currentWordLength > maxWordLength){
                    maxWordLength = currentWordLength;
                    maxWord = inputStr.substring(wordStartPos, wordEndPos);
                }
                //重置单词记录状态
                startFlag = false;
                console.log(`当前单词:${inputStr.substring(wordStartPos, wordEndPos)}  长度:${currentWordLength}`);
            }
        }
        position++;
    }
    
    
    console.log(`最长单词是:${maxWord},长度为:${maxWordLength}`);
}
const  str = "     let           currentWordLength =         wordEndPos - wordStartPos;       1234567890abcdefghijklmn";
findTheLongestWord(str);