最後一個單詞的長度

原題

  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.算法

題目大意

  給定一個由大小寫字母組和空格組成的字符串,返回字符串中的最後一個單詞長度。spa

解題思路

  先從後找第一個字母的位置x,若是沒有找到就返回0,若是找到,再找第一個空格的位記爲y(y多是-1,由於沒有找到空格),返回結果x-y。.net

代碼實現

算法實現類code

public class Solution {
    public int lengthOfLastWord(String s) {

        int index = s.length() - 1;

        // 從後面向前找第一個不是' '的字符
        while (index >=0 && s.charAt(index) == ' ') {
            index--;
        }

        if (index < 0) {
            return 0;
        }

        int tmp = index;

        // 執行到下面說明存在最後一個單詞

        // 從後面向前找第一個是' '的字符
        while (index >=0 && s.charAt(index) != ' ') {
            index--;
        }

        return tmp - index;
    }
}
相關文章
相關標籤/搜索