我自己用split写的,系统给的评级,貌似效率偏低。
public class LengthOfLastWord_2 {
public static void main(String args[]) {
String s = "luffy is still joyboy";
System.out.println(len(s));
}
static int len(String s) {
String hah[] = new String[] {};
hah = s.split(" ");
if(hah.length==0)return 0;
int count = hah.length-1;
count = hah[count].length();
return count;
}
}
推荐一个作者:大佬用的是“双指针”法...
作者:guanpengchn
链接:https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public class LengthOfLastWord {
public static void main(String args[]) {
String s = "luffy is still joyboy";
System.out.println(len(s));
}
static int len(String s) {
int right = s.length()-1;
while(right>=0 && s.charAt(right)==' ')right--;
if(right<0)return 0;
int left = right;
while(left>=0 && s.charAt(left)!=' ')left--;
return right-left;
}
}

本文对比了两种计算字符串中最后一个单词长度的方法,一种使用split()效率较低,另一种通过双指针技巧实现,提高了代码效率。作者guanpengchn提供了更高效的解决方案。
952

被折叠的 条评论
为什么被折叠?



