zoukankan      html  css  js  c++  java
  • leetcode -- 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.

    [解题思路]

    从最后往前扫描。处理如下三种模式:(*表示若干个空格)
    1. "*"
    2. "*word"
    3. "*word*"
    4. "word*"

     1 public int lengthOfLastWord(String s) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         if(s.length() == 0)
     5             return 0;
     6         
     7         String[] strs = s.split(" ");
     8         for(int i = strs.length - 1; i >= 0; i++){
     9             if(isWord(strs[i])){
    10                 return strs[i].length();
    11             }
    12         }
    13         return 0;
    14     }
    15     
    16     public boolean isWord(String s){
    17         if(s.length() == 0)
    18             return false;
    19             
    20         for(int i = 0; i < s.length(); i++){
    21             if((s.charAt(i) < 'a' && s.charAt(i) > 'z') ||
    22                 (s.charAt(i) < 'A' && s.charAt(i) > 'Z')){
    23                     return false;
    24                 }
    25         }
    26         
    27         return true;
    28     }
    29 }
  • 相关阅读:
    使用eclipse新建一个SWT工程
    C++类的构造函数
    D3D编程的常见报错及解决
    D3D窗口的初始化
    C++联合体的内存使用
    QT程序如何编译
    Restart
    HTML
    信号、槽位及布局
    QT对话框程序
  • 原文地址:https://www.cnblogs.com/feiling/p/3248241.html
Copyright © 2011-2022 走看看