法一: 反向遍历
解题思路:
1.字符串末尾的空格长度要减去
2.指针从末尾开始遍历index:len(S)-1,若末尾为空格,则指针往左移index--,直到不为空格时的index值
3.然后遍历到index>=&&s[index]不为空格就累加该末尾子字符串长度ans,指针index往左遍历,index--
tips:ans作为出参变量名,不需要在函数内声明,直接使用即可
func main(){
var strs string
strs="luffy is still joyboy"
ans3:=lengthOfLastWord(strs)
fmt.Println(ans3)
}
func lengthOfLastWord(s string) (ans3 int) {
index:=len(s)-1
for s[index]==' ' {
index--
}
for index>=0&&s[index]!=' ' {
ans3++
index--
}
return
}
时间复杂度:O(N):N即末尾空格长度+末尾子字符串长度
空间复杂度:O(1)