You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现连续元音仅首字母添加opp的Oppengloppish编码需求

解决Oppengloppish语言转换中连续元音重复添加"opp"的问题

你的代码目前会给每个元音都前置"opp",但需求是连续元音仅在第一个前添加"opp",后续元音跳过。比如输入team时当前输出toppeoppam,正确输出应为toppeam;score的输出符合预期是因为其中的元音不连续。

问题根源

原代码遍历每个字符时,只要检测到元音就插入"opp",没有判断当前元音是否处于连续元音序列中,导致连续元音重复添加前缀。

修正后的代码

#include <iostream>
#include <string>
#include <algorithm>

bool is_vowel(char c)
{
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
using namespace std;
int main()
{
    const string vowel_prefix = "opp";
    string word, oword;
    cin >> word;
    
    // 预分配足够内存,按无连续元音的最坏情况计算
    oword.reserve(word.length() + count_if(word.begin(), word.end(), is_vowel) * 3);
    
    for (size_t i = 0; i < word.size(); ++i) {
        char current_char = word[i];
        // 仅当当前是元音,且不是连续元音的后续字符时,添加"opp"
        if (is_vowel(current_char)) {
            if (i == 0 || !is_vowel(word[i-1])) {
                oword += vowel_prefix;
            }
        }
        oword += current_char;
    }
    
    cout << oword << endl;
}

关键改动说明

  1. 逻辑调整:先判断是否需要添加前缀,再将当前字符加入结果,避免原代码中insert操作的位置混淆,逻辑更清晰。
  2. 连续元音判断:仅在两种情况下添加"opp":
    • 当前是单词的第一个字符且为元音
    • 当前是元音,且前一个字符不是元音
  3. 内存预分配修正:"opp"是3个字符,原代码的*2计算错误,这里按无连续元音的最坏情况预分配,保证内存效率。
  4. 变量名优化:将vowel_postfix改为vowel_prefix,语义更准确(因为是添加在元音前面)。

测试验证

  • 输入team:输出toppeam(符合预期)
  • 输入score:输出scopporoppe(符合预期)

内容的提问来源于stack exchange,提问作者jack is carbon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:40:34