Leet Code OJ 58. Length of Last Word [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 58. Length of Last Word [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
翻譯:
給定一個字符串,它是由大小寫字母和空格組成的,返回字符串中最后一個單詞的長度。
如果最后一個單詞不存在,就返回0.
提示:一個單詞是指一個只由非空格的字符組成的字符串序列。
分析:
有一點題目中沒有說明的是,假如最后是空格的話,如何處理。經過測試,發現最后是空格的話,還是返回上一個單詞的長度,并不會清零。
代碼:
public class Solution {public int lengthOfLastWord(String s) {char[] arr=s.toCharArray();int count=0;boolean needClean=false;for(int i=0;i<arr.length;i++){if(arr[i]!=' '){if(needClean){count=0;needClean=false;}count++;}else{needClean=true;}}return count;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 58. Length of Last Word [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 27. Rem
- 下一篇: Leet Code OJ 66. Plu