题解 | #华为no.1 字符串最后一个单词的长度#
字符串最后一个单词的长度
http://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
暴力解法,初始化两个指针,low和fast;fast遍历char数组,如果==' ',low==fast;遍历完成后,如果low==0说明没有空格,直接输出length;如果!=0,输出length-1-low,得到答案。
System.out.println("请输入字符串");
StringBuilder sb = new StringBuilder();
//输入扫描进去
sb.append(sc.nextLine());
char[] c = new char[sb.length()];
c = sb.toString().toCharArray();
int fast = 0;
int low = 0;
for(;fast<c.length;fast++) {
if (c[fast]==' ') {
low = fast;
}
}
if (low!=0) {
System.out.println(c.length-1-low);
} else {
System.out.println(c.length);
}
查看11道真题和解析