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

  • 相关阅读:
    第十一节 CSS引入的三种方式
    第十节 表单
    第九节 页面布局(简历)
    第八节 HTML表格
    第七节 列表标签
    第六节 链接标签
    第五节 插入图的img标签
    WordPress 全方位优化指南(下)
    Cloud Insight!StatsD 系监控产品新宠!
    WordPress 全方位优化指南(上)
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002364.html
Copyright © 2011-2022 走看看