zoukankan      html  css  js  c++  java
  • Length of Last Word

    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.

    这一题很简单,但是有一个地方很无聊。 就是可能在一个word之后有很多空格,但是当你要得到last word length的时候 是要忽略这些空格的。 所以首先除去末尾的空格。

     1 public class Solution {
     2     public int lengthOfLastWord(String s) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(s == null || s.length() == 0) return 0;
     5         int i = 0;
     6         int tail = 0;
     7         for(;tail < s.length(); tail ++){
     8             if(s.charAt(s.length() - tail - 1) != ' ') break;
     9         }
    10         while(i < s.length() - tail)
    11         {
    12             if(s.charAt(s.length() - tail - i - 1) == ' ') return i;
    13             i ++;
    14         }
    15         return s.length() - tail;
    16     }
    17 }

    第三遍:

     1 public class Solution {
     2     public int lengthOfLastWord(String s) {
     3         if(s == null || s.length() == 0) return 0;
     4         int right = s.length() - 1;
     5         while(right > -1 && s.charAt(right) == ' ') right --;
     6         int left = right;
     7         while(left > -1 && s.charAt(left) != ' ') left --;
     8         return right - left;
     9     } 
    10 }
  • 相关阅读:
    Django remedy a security issue refer dos attack
    AppScan8.7的两个细节亮点
    redis的使用
    IDEA使用技巧
    记录tips
    Scala实现wordcount
    Scala学习笔记1
    linux系统下访问window本地数据库
    python国内使用豆瓣下载源和linux常用的命令
    hadoop集群开启和停止执行命令
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3351227.html
Copyright © 2011-2022 走看看