LeetCode 58. Length of Last Word(最後一個單詞長度)

題目描述:

    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.

例子:

Input: "Hello World"
Output: 5

分析:
    題意:給定一個字符串s,只包含大小寫字母表和空格。返回最後一個單詞字符串的長度。
    思路:我們對字符串進行逆序遍歷,顯然需要找到最後一個單詞之前的空格。假設字符串總長度爲n,我們用flag表示是否出現字母,則分爲4種情況討論:① s[i] == ' '、flag == false,說明還沒有遇到字母,跳過;② s[i] == ' '、flag == true,說明找到了最後的單詞、且遇到了空格,結束搜索,跳出;③ s[i] != ' '、flag == false,說明遇到了最後單詞的第一個字母,但是搜索還沒結束,答案加一,且flag置爲true;④ s[i] != ' '、flag == true,說明遇到了最後單詞中間的字母,但是搜索還沒結束,答案加一。
    最後返回答案。時間複雜度爲O(n)。

代碼:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int lengthOfLastWord(string s) {
		int n = s.length();
		// Exceptional Case: 
		if(n == 0){
			return 0;
		}
		bool flag = false;
		int ans = 0;
        for(int i = n - 1; i >= 0; i--){
			if(s[i] == ' ' && !flag){
				continue;
			}
			else if(s[i] == ' ' && flag){
				break;
			}
			else if(s[i] != ' ' && !flag){
				flag = true;
				ans++;
			}
			else if(s[i] != ' ' && flag){
				ans++;
			}
		}
		return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章