zoukankan      html  css  js  c++  java
  • 58. Length of Last Word(easy, 字符串问题)

    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. 先消除字符串首、尾的空格;
    2. 再从字符串尾向首查找,直到找到空格或者指针到队首都没找到空格为止,返回最后一个 word 的长度.

    我方法,我代码:
    (O(n)) time, (O(1)) extra space.

    // 解题关键:消除 s 的首尾空格
    int lengthOfLastWord(string s) {
    	const int n = s.size() - 1;
    	if (s.size() == 0) return 0;
    
    	int begin = 0, end = n;
    
    	//消除字符串首尾空格
    	if (s[0] == ' ') {
    		for (int i = 0; i < s.size(); i++) {
    			if (s[i] != ' ') {
    				begin = i;
    				break;
    			}
    		}
    	}
    
    	if (s[n] == ' ') {
    		for (int i = n; i >= 0; i--) {
    			if (s[i] != ' ') {
    				end = i;
    				break;
    			}
    		}
    	}
    
    	// 从尾部开始查找
    	for (int i = end; i >= begin; i--) {
    		if (s[i] == ' ') return end - i;
    		else if (i == begin) return end - begin + 1;
    	}
    }
    
  • 相关阅读:
    7.12.2
    7.12.1
    7.11.8
    循环测试条件前缀和后缀的区别
    7.11.7 两个版本
    7.11.5
    7.12 vowels.c 程序
    7.11 animals.c 程序
    7.6.2 break 语句
    7.10 break.c 程序
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7492054.html
Copyright © 2011-2022 走看看