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. 

 Example: 


Input: "Hello World"
Output: 5
複製代碼

翻譯:

給定一個字符串s由大寫/小寫字母和空空格字符' '組成,返回字符串中最後一個單詞的長度。
若是最後一個單詞不存在,返回0。
注意:單詞被定義爲由非空格字符組成的字符序列。
例子: 輸入:「Hello World」 輸出:5 給定整數數組號,找到具備最大和的相鄰子數組(至少包含一個數字)並返回其和。數組


解題思路

本題是很簡單,咱們只要遍歷字符,統計不爲空字符的字數,遇到空字符則從新計數,並記錄上一次操做的數量,若是下一次爲空串,則沿用上一次的結果。固然能夠直接用string的方法來實現。bash

解題方法

  1. 按照咱們的思路來編輯,代碼以下ui

    if (s == null || "".equals(s)) {
            return 0;
        }
        int count = 0;
        int lastCount = count;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                lastCount = count == 0 ? lastCount : count;
                count = 0;
                continue;
            }
            count++;
        }
        return count == 0 ? lastCount : count;
    複製代碼

    時間複雜度: 該方案用了循環m因此f(n)=(n)=n;因此O(f(n))=O(n),即T(n)=O(n)spa

    空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);翻譯

  2. 借用String的方法,代碼以下code

    if (s == null || "".equals(s)) {
            return 0;
        }
        s = s.trim();
    
        return s.length() - s.lastIndexOf(" ") - 1;
    
    複製代碼

    時間複雜度: 該方案用了循環m因此f(n)=(n)=n;因此O(f(n))=O(n),即T(n)=O(n)字符串

    空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);string

總結

本題的大體解法如上所訴,內容很簡單,只要獲取最後一個非空串的字符長度,特別要注意最後全是空字符的狀況,那麼是往前沿哦。ast

相關文章
相關標籤/搜索