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));
        }
    }
  • 相关阅读:
    hdu1430 魔板(康拓展开 bfs预处理)
    网络流EdmondsKarp算法模板理解
    poj3020 建信号塔(匈牙利算法 最小覆盖边集)
    bzoj 2465 小球
    bzoj 1822 冷冻波
    bzoj 1040 骑士
    Codeforces Round #460 (Div. 2)
    bzoj 1072 排列perm
    Codeforces Round #459 (Div. 2)
    bzoj 1087 互不侵犯King
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7531581.html
Copyright © 2011-2022 走看看