Length of Last Word

来源:互联网 发布:linux基础教程第二版 编辑:程序博客网 时间:2024/06/14 00:11

这里写图片描述

题目要求:
  在给定字符串中找出最后一个word的长度,word指被空格符“ ”截断的部分。即”Hello World”
中最后一个word是指World,所以其长度是5。

解题思路:
设置一个标识 reset(当遇到非空格符时根据reset来判断是否要重置str)。
比如上面的”Hello World”,当遇到第一个字符H时,reset为false。将H赋值给str,往后走遇到第一个空格符“ ”时,此时将reset赋值true。当再次遇到非空格符W时,因为reset为true,此时重置str。然后重复上述过程得到答案。

AC代码:

public class Solution {    public int lengthOfLastWord(String s) {      boolean reset = false;        String str = "";        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if (' ' != c) {                if (reset) {                    str = "";                    reset = false;                }                str += c;            }            else {                reset = true;            }        }        return str.length();    }}
0 0