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.
    
    Have you met this question in a real interview? Yes
    Example
    Given s = "Hello World", return 5.
    
    Note
    A word is defined as a character sequence consists of non-space characters only.

    题解

    关键点在于确定最后一个字符串之前的空格,此外还需要考虑末尾空格这一特殊情况,故首先除掉右边的空白字符比较好。

    JAVA:

    public class Solution {
        /**
         * @param s A string
         * @return the length of last word
         */
        public int lengthOfLastWord(String s) {
            if (s == null | s.isEmpty()) return 0;
    
            // trim right space
            int begin = 0, end = s.length();
            while (end > 0 && s.charAt(end - 1) == ' ') {
                end--;
            }
            // find the last space
            for (int i = 0; i < end; i++) {
                if (s.charAt(i) == ' ') {
                    begin = i + 1;
                }
            }
    
            return end - begin;
        }
    }

    源码分析

    两根指针。

    复杂度分析

    遍历一次,时间复杂度 O(n).

  • 相关阅读:
    mui 页面跳转
    mui 下拉刷新
    mui 上拉加载更多
    mui 页面传值
    mui 监听app运行状态
    mui webview操作
    mui ajax方法
    ionic 图片加载失败,显示默认图片代替
    mui 侧滑菜单
    ionic中关于ionicView 的生命周期
  • 原文地址:https://www.cnblogs.com/lyc94620/p/10077127.html
Copyright © 2011-2022 走看看