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.

    这道题整体很简单

    刚开始这道题想的太简单了,首先最开始的想法是得知s的长度,然后从头开始遍历找到最后一个空格的位置,作减法就可以得到最后单词的长度

    然而忽略了,如果这个字符串结尾有空格的情况。如“a    ”

    于是改变思路,从后面开始遍历,找到最后一个单词的最后一个字符开始计数,然后依次向前知道遇到第一个空格。

    下面附上代码:

    public static int lengthOfLastWord(String s) {
    
    		int length = 0;
    		char[] chars = s.toCharArray();
    		for (int i = s.length() - 1; i >= 0; i--) {
    			if (length == 0) {
    				if (chars[i] == ' ') {
    					continue;
    				} else {
    					length++;
    				}
    			} else {
    				if (s.charAt(i) == ' ') {
    					break;
    				} else {
    					length++;
    				}
    			}
    		}
    
    		return length;
    	}
    

      

  • 相关阅读:
    UVa 839 -- Not so Mobile(树的递归输入)
    UVa 548 -- Tree
    UVA 122 -- Trees on the level (二叉树 BFS)
    UVa679 小球下落(树)
    POJ 2255 -- Tree Recovery
    POJ 1451 -- T9
    POJ 2513 -- Colored Sticks
    STL -- heap结构及算法
    nginx利用try_files实现多个源
    nginx location的优先级
  • 原文地址:https://www.cnblogs.com/gracyandjohn/p/4505554.html
Copyright © 2011-2022 走看看