【发布时间】:2019-03-13 13:00:01
【问题描述】:
我有一个编程问题,我应该编写一个程序来计算不是“a”、“e”、“i”、“o”的字母对(彼此相邻的字母)的数量, 'u'(元音)。
例子:
- jas 0
- olovo 0
- skok 1 (sk)
- stvarnost 4(st、tv、rn、st)
输入由组成单词不超过 200 个字符的小字母组成,输出应输出非元音字母对的数量(a、e、i、o、u)。
时间限制:
- 1 秒
内存限制:
- 64 MB
我遇到的问题中提供的示例:
- 输入 skok
- 输出 1
但是,当我输入“skok”字样时,程序无法运行(它似乎一直在后台运行,但屏幕上没有显示任何内容)。然而,“stvarnost”(现实)这个词有效,显示“4”——正如问题中给出的那样。
在 10 个测试用例中,两个测试用例给了我正确的输出,一个给我错误的输出,另外七个测试用例告诉我我已经超过了我的时间限制。
现在,我还想要一个关于如何避免超出给定时间限制的建议,以及如何在下面的程序中解决它。
这是我开始的代码:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char zbor[200];
cin.get(zbor, 200);
int length = strlen(zbor);
int j_value = 0;
int check_pairs = 0;
int pairs = 0;
int non_vowels = 0;
for (int i = 0; i < length; i++) {
if (zbor[i] == 'a' || zbor[i] == 'e' || zbor[i] == 'i' || zbor[i] == 'o' || zbor[i] == 'u') {
continue;
} else {
non_vowels++;
for (int j = i + 1; j < length; j++) {
if (zbor[j] == 'a' || zbor[j] == 'e' || zbor[j] == 'i' || zbor[j] == 'o' || zbor[j] == 'u') {
break;
} else {
non_vowels++;
if (non_vowels % 2 != 0) {
check_pairs = non_vowels / 2 + 1;
} else {
check_pairs = non_vowels / 2;
}
if (pairs < check_pairs) {
pairs++;
}
j_value = j;
}
}
i = j_value + 1;
}
}
cout << pairs;
return 0;
}
编辑:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char zbor[200];
cin.get(zbor, 200);
int length = strlen(zbor);
int pairs = 0;
int non_vowels = 0;
for (int i = 0; i < length; i++) {
if (zbor[i] == 'a' || zbor[i] == 'e' || zbor[i] == 'i' || zbor[i] == 'o' || zbor[i] == 'u') {
non_vowels = 0;
continue;
} else {
non_vowels++;
if (non_vowels >= 2) {
if (non_vowels % 2 != 0) {
pairs = non_vowels / 2 + 1;
} else if (non_vowels % 2 == 0) {
pairs = non_vowels / 2;
}
}
}
}
cout << pairs;
return 0;
}
使用以下答案的代码片段(bruno 和 Ozzy's)编辑了代码,这是有效的最终版本:
#include <iostream>
#include <string.h>
using namespace std;
bool vowel(char c) {
switch(c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
int main()
{
char zbor[200];
cin.get(zbor, 200);
int N = strlen(zbor);
int non_vowels = 0;
int pairs = 0;
for (int i = 0; i < N; i++) {
if (!vowel(zbor[i])) {
non_vowels = 0;
} else {
non_vowels++;
if (!vowel(zbor[i])) {
non_vowels = 0;
} else {
non_vowels++;
if (non_vowels > 1) {
pairs++;
}
}
}
}
cout << pairs;
return 0;
}
【问题讨论】:
-
我没有看到任何问题,但它看起来像是调试器的工作。
-
研究
std::adjacent_find -
可以在评论区分享问题链接吗?
-
听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs 和 Debugging Guide
-
每次到达非元音时增加
non_vowels,以检查奇偶校验不允许检查非元音是否连续。你的算法错了
标签: c++ arrays string char word