58. Length of Last Word

/*
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.
*/
/*
Thinking:
使用系統(tǒng)函數(shù),切分成數(shù)組,計(jì)算最后一個(gè)的長度即可。
不使用系統(tǒng)函數(shù),反向遍歷,遇到空格則終止,但要考慮從不是空格的位置開始。
*/

func lengthOfLastWord(_ s: String) -> Int {
    let length = s.lengthOfBytes(using: .ascii)
    guard length > 0 else {
        return 0
    }

    let charArrays = s.characters
    var lastWordLength = 0
    for i in stride(from: length - 1, through: 0, by: -1) {
        let index = charArrays.index(charArrays.startIndex, offsetBy: i)
        if charArrays[index] != " " {
            lastWordLength += 1
        }
        else {
            if lastWordLength != 0 {
                break
            }
        }
    }

    return lastWordLength
}

print(lengthOfLastWord("abc def"))
print(lengthOfLastWord(""))
print(lengthOfLastWord(" "))
print(lengthOfLastWord("abc"))
print(lengthOfLastWord("abc def   ghi  "))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容