其实是道水题,但是就是因为是水题,大意了,没有注意各种极端情况。。比如
"", " ", "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 ")); } }