[leetcode] Length of Last Word

早过忘川 提交于 2020-12-12 14:58:01

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("  "));

	}
}



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!