1. 程式人生 > 實用技巧 >leetcode 58. Length of Last Word

leetcode 58. Length of Last Word

Given a stringsconsists 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 amaximal substringconsistingof non-space characters only.

Example:

Input: "Hello World"
Output: 5

題目難度:簡單題

解法一:從前往後掃描。

 1 int lengthOfLastWord(string s) {
 2         int cnt = 0;
 3         int curr = 0; //用於記錄當前字串的長度
 4         for (int i = 0; i < s.length(); ++i) {
 5             if (s[i] == ' ') {
 6                 if (curr != 0) {
 7                     cnt = curr;
8 } 9 curr = 0; 10 } else { 11 ++curr; 12 } 13 } 14 if ((s.length() > 0) && (s[s.length() - 1] != ' ')) { //如果最後一個字元不是空格,那麼替換成最後字串的長度 15 cnt = curr; 16 } 17 return cnt; 18 }

解法二:從後往前掃描

 1 int lengthOfLastWord(string s) {
 2         int cnt = 0;
 3         int index = s.length() - 1;
 4         while (index >= 0 && (s[index] == ' ')) index--;
 5         while (index >= 0 && s[index] != ' ') {
 6             --index;
 7             cnt++;
 8         }
 9         return cnt;
10     }