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",
    return5.

    https://oj.leetcode.com/problems/length-of-last-word/

    思路:从后向前扫描,定位lastword然后记录其长度。

    public class Solution {
    	public int lengthOfLastWord(String s) {
    		if (s == null || s.length() < 1)
    			return 0;
    		int n = s.length();
    		int i;
    		int len = 0;
    		boolean in = false;
    		for (i = n - 1; i >= 0; i--) {
    			if (!in && s.charAt(i) != ' ') {
    				in = true;
    			}
    			if (in && s.charAt(i) != ' ') {
    				len++;
    			}
    			if (in && s.charAt(i) == ' ')
    				break;
    		}
    
    		return len;
    
    	}
    
    	public static void main(String[] args) {
    		System.out.println(new Solution().lengthOfLastWord("Hello World"));
    		System.out.println(new Solution().lengthOfLastWord("Hello  World  "));
    		System.out.println(new Solution().lengthOfLastWord("Hello  a  "));
    		System.out.println(new Solution().lengthOfLastWord(""));
    		System.out.println(new Solution().lengthOfLastWord("  "));
    
    	}
    }

    第二遍记录:

      改了下代码,注意从后遍历时j>=0的越界判断不要忘记了。

    public class Solution {
        public int lengthOfLastWord(String s) {
            if(s==null||s.length()==0)
                return 0;
            int n = s.length();
            int j = n-1;
            while(j>=0&&s.charAt(j)==' ')
                j--;
            
            int len =0;
            while(j>=0&&s.charAt(j)!=' '){
                len++;
                j--;
            }
            return len;
        }
    }
  • 相关阅读:
    苹果 01背包
    Robberies 01背包变形 hdoj
    01背包
    小希的迷宫--并查集
    德克萨斯长角牛 --最短路径
    1596 最短路径的变形
    hibernate重要知识点总结
    Apache与Tomcat整合的配置
    java串口通讯环境配置
    使用spring的aop对Struts2的Action拦截后出现依赖注入为空问题
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810780.html
Copyright © 2011-2022 走看看