2016年12月13日 星期二

[LeetCode] 58. Length of Last Word

轉自LeetCode

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.
<Solution>

不難,就是字串的處理

先看一下有哪些情況

"hello"
""
"hello world"
"a "
" a"
"     "

根據測資,解題想法如下
  • 因為是要看最後一個 word,所以從後面往前找
  • 遇到空白就略過,如果都沒遇到字元,就回傳0
  • 找到字元後,就往前找到空白直到字元用完
code 如下

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;
}
};

沒有留言:

張貼留言