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.

     1 public class Solution {
     2     public int lengthOfLastWord(String s) {
     3         if(s == null || s == " ")
     4             return 0;
     5         
     6         char[] arr = s.trim().toLowerCase().toCharArray();
     7         int count = 0;
     8         for(int i = 0; i < arr.length; i++){
     9             char c = arr[i];
    10             if((c >= 'a' && c <= 'z')){
    11                 count++;
    12             }else{
    13                 count = 0;
    14             }
    15         }
    16         return count;
    17     }
    18 }
     1 public class Solution {
     2     public int lengthOfLastWord(String s) {
     3         if(s == null || s == " ")
     4             return 0;
     5         
     6         String[] arr = s.split(" ");
     7         
     8         if(arr.length != 0)
     9             return arr[arr.length -1].length();
    10         else 
    11             return 0;
    12     }
    13 }
  • 相关阅读:
    数值的整数次方
    Grid Sorting
    第K小的数
    图形学变换矩阵的分解
    神经网络理论简介(三)
    神经网络理论简介(二)
    神经网络理论简介(一)
    C/C++的内存对齐
    strcpy的实现
    C++对象模型简析
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3537040.html
Copyright © 2011-2022 走看看