题目描述
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
Example:
Input: "Hello World" Output: 5
解题思路1: 字符串分隔法
这个题如果使用语言自带的字符串分隔方法非常简单, 将字符串分隔为数组, 获取最后一个item的length就是结果, 这个方法主要要过滤掉最后一个为空格时,item为""字符串的情况
时间复杂度: O(1)
示例代码1
func lengthOfLastWord(_ s: String) -> Int {
var result = 0
var tempArr = s.components(separatedBy: " ")
tempArr = tempArr.filter { (str) -> Bool in
return str.count > 0
}
if let last = tempArr.last {
result = last.count
}
return result
}
解题思路2: 遍历法
如果不用语言自带的字符串分隔方法,我们就可以直接倒序遍历这个字符串, 当我们的计数器为不为0且当前字符时空字符时, 我们就找到了最后一个子串
时间复杂度: O(n)
示例代码2:
func lengthOfLastWord(_ s: String) -> Int {
var result = 0
let tempArr = Array(s)
for i in 0..<tempArr.count {
let temp = tempArr[tempArr.count-i-1]
if temp != " " {
result = result + 1
}else {
if result != 0 {
return result
}
}
}
return result
}