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));
        }
    }
  • 相关阅读:
    排球运动规则简介
    我与计算机
    我和电脑的不解之缘
    作业
    怎样成为一个高手 观后感
    本周作业
    作业个人
    本周作业
    本周总结
    本周总结(13周)
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7531581.html
Copyright © 2011-2022 走看看