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;
    	}
    }
    
  • 相关阅读:
    Codeforces 220C
    Codeforces 697D
    HDU 4417
    Codeforces 396C
    Codeforces 246C
    HDU 6333
    HDU 3389
    总结:树上启发式合并
    HDU 6319
    Codeforces 1009G
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7492054.html
Copyright © 2011-2022 走看看