gpt4 book ai didi

c++ - 这被认为是硬编码吗?

转载 作者:行者123 更新时间:2023-11-30 02:33:28 27 4
gpt4 key购买 nike

我有一个任务,我们需要获取一个字符串 s 和一个位置 pos,并且我需要“收集”该位置的所有整数。例如,说 3 abcdef123 应该输出 abc123def(整数从位置 3 开始)。接受这些参数的主要位置未显示。

示例输入可能如下所示:

5 ab1cdefgh (the 1 moves to the 5th index)

6 1abcdefgh (the 1 moves to the 6th index)

8 1abcdefgh (the 1 moves to the end)

8 abcdefgh1 (the 1 doesn't move)

0 1abcdefgh

-1 (quit)

void gatherDigits(std::string& s, const int pos) {

int ints = 1;
int size = s.size();

for (int i = 0; i < size; i++) {
if (std::isdigit(s.at(i))) {
ints++;
}
}

s = "";
char letter;
char l;
int count = 0;
for (letter = 'a'; letter <= 'z'; letter++) {
if (count == pos) {
l = letter;
break;
}
s = s + letter;
count++;
}

for (int i = 1; i < ints; i++) {

if (i == 10) {
s = s + std::to_string(0);
}
else {

s = s + std::to_string(i);
}
}

for (int i = pos + ints; i < size + 1; i++) {
s = s + l;
l++;
}
}

但是,我遇到了一个困境。我不确定这是否被认为是硬编码(我们明确指示不要硬编码)。我们被允许使用的唯一变量是 int 和 char,这就是我以这种方式设置它的原因。此外,所有输入示例都是小写的 a-z 和 0-9 整数。我们的代码必须在 O(n^2) 时间内运行。

一个更困难的输入可能是这样的:

6 12ab3cdefghij456klm7n8op9q0

建议的解决方案涉及使用交换语句。除了缺少交换语句外,我的代码满足所有其他要求。最后,我只想问:这是否符合硬编码的条件?

最佳答案

你所做的硬编码是期望字符串中的字母以 a 开头并构建一个序列 abcd.... 并且你的数字形式 1234...。我不能说这是否会被您的主管认为是硬编码,但它肯定会使您的代码非常不灵活,并且只有在问题描述中明确说明这些属性时我才会这样做。

关于交换的部分可能是指将实际字符交换到字符串中的适当位置,而不是拆除整个字符串并创建一个新字符串,这只有在上述假设下才有可能。

正如评论中所暗示的那样,如果允许您使用标准算法,则可以大大简化和概括您的解决方案。一种可能性是例如是:

void gatherDigits(std::string& s, const int pos) {
//moves all digits to the start of the range and returns the number of digits
int cnt = std::stable_partition(s.begin(), s.end(), ::isdigit) - s.begin();

//make sure we don't write past the end of the string
assert(pos+cnt < s.size());

//rotates the string such that the digits start at the correct place
std::rotate(s.begin(), s.begin() + cnt, s.begin() + pos + cnt);
}

关于c++ - 这被认为是硬编码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35424756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com