zoukankan      html  css  js  c++  java
  • [Leetcode 3] 58 Length of Last Word

    Problem:

    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.

    Analysis:

    Start from the last position of the given String. We not start counting until meet with a non-' ' character. Then we start count the occurace of no-' ' character until 1. meet with a ' ' or 2. reach the head of the string. Some special cases may be: S="", S="       ", S="ssssss"

    The time complexity in worst case is O(n), the space complexity is O(n), n is the number of characters of the String

    Code:

    public class Solution {
        public int lengthOfLastWord(String s) {
            // Start typing your Java solution below
            // DO NOT write main() function
            if (s.equals("")) return 0;
            
            int p, len=0;
            
            for (p = s.length()-1; p>=0 && s.charAt(p)==' '; p--) ;
                
            for (len=0; p>=0 && s.charAt(p)!=' '; len++, p--) ;
            
            return len;
        }
    }

    Attention:

    Judging whether S is an "", can't use S==null, because S is a reference which always isn't null, use S.equals("") or S.length()==0 to instead

    Java String doesn't support [] operator, use charAt(int i) to instead

  • 相关阅读:
    神秘现象?多种情况比较
    [备忘]C++BUILDER的文件操作
    缘起
    [备忘]一个二维数组的冒泡排序
    无可救药地买入NDSL
    递归的实质
    [网游计划第九、十天]能力有限,做些小品
    大学有救
    struts2+convertion实现struts.xml的零配置
    BSD下的超级终端
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002364.html
Copyright © 2011-2022 走看看