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 }
  • 相关阅读:
    深度学习
    定义一个变长数组和常量引用参数
    深度神经网络tricks and tips
    PCA whitening
    反向传播
    激活函数
    C++中模板的使用
    数据结构 (二叉树)1
    C++中的函数指针和函数对象总结
    从头到尾彻底解析Hash表算法
  • 原文地址:https://www.cnblogs.com/feiling/p/3248241.html
Copyright © 2011-2022 走看看