现在的位置: 首页 > 综合 > 正文

LeetCode的LastWord

2019年04月17日 ⁄ 综合 ⁄ 共 386字 ⁄ 字号 评论关闭

其实是道水题,但是就是因为是水题,大意了,没有注意各种极端情况。。比如

"", " ", "a b ","a      b                           "

吸取教训。。

import java.util.*;

public class LastWord {
	
    public int lengthOfLastWord(String s) {
    	if(s.length() == 0)
    		return 0;
    	
    	int e = s.length() - 1;
    	while(e>=0 && s.charAt(e) == ' ')
    		e--;
    	
    	
    	int k = 0;
    	while(k <= e && (s.charAt(e -k) != ' '))
    	{
    		k++;
    	}
    	
    	return k;
    }
    
    
    public static void main(String[] args)
    {
    	LastWord app = new LastWord();
    	System.out.println(app.lengthOfLastWord("a  few     "));
    }
}

抱歉!评论已关闭.