题目及测试
package pid058;
/* 58. 最后一个单词的长度
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
示例 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为4。
示例 3:
输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。
提示:
1 <= s.length <= 104
s 仅有英文字母和空格 ' ' 组成
s 中至少存在一个单词
*/
public class main {
public static void main(String[] args) {
String [] testTable = {"luffy is still joyboy"," fly me to the moon "};
for (String ito : testTable) {
test(ito);
}
}
private static void test(String ito) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
System.out.print(ito);
System.out.println();
//开始时打印数组
rtn= solution.lengthOfLastWord(ito);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn=" );
System.out.print(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功,1ms,较慢)
顺序遍历字符串
package pid058;
class Solution {
public int lengthOfLastWord(String s) {
int length = s.length();
if(length == 0){
return 0;
}
int result = 0;
int max = 0;
for(int i=0;i<length;i++){
if(s.charAt(i)==' '){
if(max != 0){
result = max;
max = 0;
}
}else{
max++;
}
}
if(max != 0){
result = max;
}
return result;
}
}
解法2(别人的)
反向遍历
题目要求得到字符串中最后一个单词的长度,可以反向遍历字符串,寻找最后一个单词并计算其长度。
由于字符串中至少存在一个单词,因此字符串中一定有字母。首先找到字符串中的最后一个字母,该字母即为最后一个单词的最后一个字母。
从最后一个字母开始继续反向遍历字符串,直到遇到空格或者到达字符串的起始位置。遍历到的每个字母都是最后一个单词中的字母,因此遍历到的字母数量即为最后一个单词的长度。
class Solution {
public int lengthOfLastWord(String s) {
int index = s.length() - 1;
while (s.charAt(index) == ' ') {
index--;
}
int wordLength = 0;
while (index >= 0 && s.charAt(index) != ' ') {
wordLength++;
index--;
}
return wordLength;
}
}