Lenghth of Last Word

Posted whatyouknow123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lenghth of Last Word相关的知识,希望对你有一定的参考价值。

description:

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

 

Thoughts:

首先,我们先要知道s的长度是否为0,如果为0的话直接返回0。否则的话,我们从最后面开始找到第一个不为“ ”的字符,如果找不到也直接返回0,否则的话我们计算从这个字符开始连续的不为“ ”的字符的长度。这个长度就是我们所求的值。

以下是我的java代码:

package easy;

public class LengthOfLastWord {
    public int lengthOfLastWord(String s) {
        int position = s.length() - 1;
        if(s.isEmpty()){
            return 0;
        }else{
            while(position >= 0){
                if(s.charAt(position) == ‘ ‘){
                    position--;
                }else{
                    break;
                }
                
            }
            if(position == -1){
                return 0;
            }else{
                 for(int i = position;i>=0;){
                     if(s.charAt(i) != ‘ ‘ ){
                         i--;
                     }else{
                         return position-i;
                     }
                 }
            }
           
        }
        return position+1;
    }    
    
    public static void main(String[] args){
        LengthOfLastWord l = new LengthOfLastWord();
        String s =" ";
        System.out.println(l.lengthOfLastWord(s));
    }
}

 

以上是关于Lenghth of Last Word的主要内容,如果未能解决你的问题,请参考以下文章

Length of Last Word

58. Length of Last Word

LeetCode 58. Length of Last Word

58. Length of Last Word

#Leetcode# 58. Length of Last Word

58. Length of Last Word [easy] (Python)