第58题:最后一个单词的长度

解题思路

58. 最后一个单词的长度

思路一:

把字符串以空格分开,然后计算出最近一串字母的长度

思路二:

从后向前遍历直到遍历到头或者遇到空格为止

代码

方法一:分割字符串
//运行时间:4ms , 内存消耗:37.2MB
class Solution {
   
	public static int lengthOfLastWord(String s) {
		String str = s.trim();
		if(str.length() == 0 ) return 0;
		String[] strs = str.split("\\s+");//  \s:匹配任何空白字符,包括空格、制表符、换页符等    +:一次或多次匹配前面的字符或子表达式
		String last_str = strs[strs.length-1];
        return last_str.length();
    }
}
方法二:从后往前遍历
//运行时间:0ms , 内存消耗:36.5MB
class Solution {
   
	public static int lengthOfLastWord(String s) {
		String str = s.trim();
		int count=0;
		for(int end = str.length()-1 ; end>=0 && str.charAt(end)!=' ' ;end--) {
			count++;
		}
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值