
2026-04-25:反转元音数相同的单词。用go语言,给定一个由小写英文单词组成的字符串,各单词之间用单空格分隔。
先统计第一个单词里出现的元音字母数量(元音为 a/e/i/o/u)。记这个数量为 k。
然后从第二个单词开始逐个处理:如果某个单词的元音数量也等于 k,就把该单词反转字母顺序;否则保持该单词不变。
最后把所有单词按原有顺序重新用空格拼接,输出结果字符串。
1 <= s.length <= 100000。
s 仅由小写的英文字母和空格组成。
s 中的单词由 单个空格 隔开。
s 不包含前导或尾随空格。
输入: s = "cat and mice"。
输出: "cat dna mice"。
解释:
第一个单词 "cat" 包含 1 个元音字母。
"and" 包含 1 个元音字母,因此将其反转为 "dna"。
"mice" 包含 2 个元音字母,因此保持不变。
最终结果字符串为 "cat dna mice"。
题目来自力扣3775。
这是一个辅助函数,作用是统计一个字符串中元音字母(a/e/i/o/u)的总个数:
代码将输入的完整字符串按单个空格切割,把连续的字符串拆分成独立的单词列表:
"cat and mice"["cat", "and", "mice"]cat;c:非元音;a:元音,计数+1;t:非元音;k = 1,并把这个值固定下来。从第二个单词开始(数组下标为1),逐个判断、处理:
a是元音,n/d非元音,元音数=1;and的字母顺序颠倒,变成dna;["cat", "dna", "mice"]。i和e是元音,元音数=2;["cat", "dna", "mice"]。将处理后的单词数组,按单个空格重新拼接成一个完整字符串:
cat dna mice。s = "cat and mice";cat dna mice。时间复杂度描述代码执行的总操作次数与输入数据规模的关系:
n成正比,复杂度为 O(n);n,复杂度为 O(n);所有步骤都是线性操作,总时间复杂度为 O(n)(n 为输入字符串的总长度)。
额外空间复杂度描述代码执行过程中,除了输入和输出外,额外占用的内存空间:
n成正比;总额外空间复杂度为 O(n)(n 为输入字符串的总长度)。
.
package main
import (
"fmt"
"slices"
"strings"
)
func countVowel(s string) (vowel int) {
for _, c := range s {
if strings.IndexRune("aeiou", c) >= 0 {
vowel++
}
}
return
}
func reverseWords(s string)string {
a := strings.Split(s, " ")
cnt0 := countVowel(a[0])
for i := 1; i < len(a); i++ {
if countVowel(a[i]) == cnt0 {
t := []byte(a[i])
slices.Reverse(t)
a[i] = string(t)
}
}
return strings.Join(a, " ")
}
func main() {
s := "cat and mice"
result := reverseWords(s)
fmt.Println(result)
}

.
# -*-coding:utf-8-*-
def count_vowel(s: str) -> int:
"""Count vowels in a string"""
vowel = 0
for c in s:
if c in "aeiou":
vowel += 1
return vowel
def reverse_words(s: str) -> str:
"""Reverse words that have the same vowel count as the first word"""
words = s.split(" ")
cnt0 = count_vowel(words[0])
for i in range(1, len(words)):
if count_vowel(words[i]) == cnt0:
# Reverse the word
words[i] = words[i][::-1]
return" ".join(words)
def main():
s = "cat and mice"
result = reverse_words(s)
print(result)
if __name__ == "__main__":
main()
.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
int countVowel(const std::string& s) {
int vowel = 0;
std::string vowels = "aeiou";
for (char c : s) {
if (vowels.find(c) != std::string::npos) {
vowel++;
}
}
return vowel;
}
std::string reverseWords(const std::string& s) {
// Split string into words
std::vector<std::string> words;
std::stringstream ss(s);
std::string word;
while (ss >> word) {
words.push_back(word);
}
if (words.empty()) {
return"";
}
int cnt0 = countVowel(words[0]);
for (size_t i = 1; i < words.size(); i++) {
if (countVowel(words[i]) == cnt0) {
// Reverse the word
std::reverse(words[i].begin(), words[i].end());
}
}
// Join the words back
std::string result;
for (size_t i = 0; i < words.size(); i++) {
if (i > 0) {
result += " ";
}
result += words[i];
}
return result;
}
int main() {
std::string s = "cat and mice";
std::string result = reverseWords(s);
std::cout << result << std::endl;
return0;
}
