算法leetcode|58. 最后一个单词的长度(rust重拳出击)



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 中至少存在一个单词

分析:

  • 面对这道算法题目,二当家的陷入了沉思。
  • 如果对语言的API比较熟,可能想到直接用空格分割字符串,然后取最后一个字符串的长度即可,但其实效率不算高。
  • 从后向前逆序遍历是个好办法。

题解:

rust:

impl Solution {
    
    
    pub fn length_of_last_word(s: String) -> i32 {
    
    
        s.as_bytes().iter()
            .rev()
            .skip_while(|&&c| c == b' ')
            .take_while(|&&c| c != b' ')
            .count() as i32
    }
}

go:

func lengthOfLastWord(s string) (ans int) {
    
    
	index := len(s) - 1
	for s[index] == ' ' {
    
    
		index--
	}
	for index >= 0 && s[index] != ' ' {
    
    
		ans++
		index--
	}
	return
}

c++:

class Solution {
    
    
public:
	int lengthOfLastWord(string s) {
    
    
		int index = s.size() - 1;
		while (s[index] == ' ') {
    
    
			--index;
		}
		int ans = 0;
		while (index >= 0 && s[index] != ' ') {
    
    
			++ans;
			--index;
		}
		return ans;
	}
};

python:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.rstrip().split(" ")[-1])


java:

class Solution {
    
    
	public int lengthOfLastWord(String s) {
    
    
		int index = s.length() - 1;
		while (s.charAt(index) == ' ') {
    
    
			--index;
		}
		int ans = 0;
		while (index >= 0 && s.charAt(index) != ' ') {
    
    
			++ans;
			--index;
		}
		return ans;
	}
}

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


猜你喜欢

转载自blog.csdn.net/leyi520/article/details/131205083
今日推荐