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;
        }
    }
  • 相关阅读:
    Python服务Debian打包新思路
    小议Python3的原生协程机制
    推送公司今日菜单内容到手机
    Python包管理工具小结
    PAT 1068. 万绿丛中一点红
    PAT 1067. 试密码
    PAT 1066. 图像过滤
    PAT 1065. 单身狗
    PAT 1064. 朋友数
    PAT 1063. 计算谱半径
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3810780.html
Copyright © 2011-2022 走看看