zoukankan      html  css  js  c++  java
  • 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));
        }
    }
  • 相关阅读:
    (个人题目)作业 题解
    P2618 数字工程
    P6394 樱花,还有你
    USACO08FEB Making the Grade G
    USACO13NOV Pogo-Cow S
    CSP2019 树上的数
    JSOI2018 潜入行动
    NOIP2017 宝藏
    SNOI2017 炸弹
    【洛谷】【最小生成树】P1195 口袋的天空
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7531581.html
Copyright © 2011-2022 走看看