题目描述:
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
思路:
给一个字符串,判定最后一个单词的字母的个数。可以从后往前计数,直到遇见空格为止。
预处理:先把字符串后面的空格都去掉:
先用length表示s的长度-1,判定这个s.charAt(length)是否等于空格,即最后一位是否为空格,如果是length--,然后继续判断,直到不是空格开始计数。
从i=length开始,i递减遍历s,如果等于空格则break,如果不等则count++
返回count即可
1 public class Solution58 { 2 public int lengthOfLastWord(String s){ 3 int count = 0; 4 if(s.isEmpty()) return 0; 5 int length = s.length()-1; 6 while(length>0 && s.charAt(length) ==' ') --length; 7 for(int i = length;i>=0;i--){ 8 if(s.charAt(i) == ' '){ 9 break; 10 }else { 11 count++; 12 } 13 } 14 //if(count == s.length()){return 0;} 15 return count; 16 } 17 public static void main(String[] args) { 18 // TODO Auto-generated method stub 19 String s = "Hello world"; 20 Solution58 solution58 = new Solution58(); 21 System.out.println(solution58.lengthOfLastWord(s)); 22 } 23 24 }
来源:https://www.cnblogs.com/zlz099/p/8144964.html