LeetCode—58. Length of Last Word

LeetCode—58. Length of Last Word

题目

https://leetcode.com/problems/length-of-last-word/description/
找出句子字符串中最后一个单词的长度。

思路及解法

很简单的题。从后向前遍历就好了,到达第一个空格就break出来。需要注意的是整个句子字符串最后是可能有有空格的,所以首先需要进行判断。

代码

class Solution {
    public int lengthOfLastWord(String s) {
        int len = s.length();
        if(len == 0) return 0;
        int i=len-1;
        for(; i>=0; i--){
            if(s.charAt(i)!=' ')
                break;
        }
        int count = 0;
        for(; i>=0; i--){
            if(s.charAt(i)==' '){
                break;
            }
            else{
                count++;
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/pnnngchg/article/details/82953096