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" ,
return5 .
Given s =
return
不難,就是字串的處理
先看一下有哪些情況
"hello"
""
"hello world"
"a "
" a"
" "
根據測資,解題想法如下
- 因為是要看最後一個 word,所以從後面往前找
- 遇到空白就略過,如果都沒遇到字元,就回傳0
- 找到字元後,就往前找到空白直到字元用完
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int lengthOfLastWord(string s) { | |
if(s.empty()) { | |
return 0; | |
} | |
int pos = s.length() - 1; | |
//> find alphabet | |
while(pos >= 0 && s[pos] == ' ') { | |
--pos; | |
} | |
if(pos < 0) { | |
return 0; | |
} | |
int right = pos; | |
//> find last word | |
while(pos >= 0 && s[pos] != ' ') { | |
--pos; | |
} | |
return right - pos; | |
} | |
}; |
沒有留言:
張貼留言