【发布时间】:2018-05-21 10:29:30
【问题描述】:
问题:
我的代码中的错误在哪里?
问题:
我想在一个字符串中找到最大的唯一子序列。示例:对于aabbaba,答案将是 2(ab 或 ba)。我想通过只迭代字符串一次来做到这一点。只允许使用小写字母。
正如@hvd 所指出的,如果其中的所有字母都是唯一的,则子序列是唯一的。字符串中可以有多次相同的唯一子序列。
方法:
- 从字符串的第一个字母开始并迭代到结尾
- 如果您还没有看到该字母,请在矢量
unique中写下该字母出现的位置 - 增加此子序列的计数
- 如果您看到了这封信,请开始一个新的子序列。使用从当前位置到最后一次出现的距离来初始化新的子序列。示例:字符串为
exampletzu。我们在第二个e。当前索引为 6。当前最大子序列为 6 (exampl)。转到 t 并创建一个新的子序列。将其初始化为 7 (xamplet)。 - 如果当前子序列等于 26,您知道可以中止,因为这是可能的最大值
代码:
#include <iostream>
#include <vector>
#include <algorithm>
//#include <bits/stdc++.h>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
typedef vector<int>::iterator it;
int length = 7;
string p = "aabbaba";
// result
vector<int> max(length, 0);
int subSeq = 0;
// alphabet
vector<int> unique(26, -1);
bool flag = false;
for (int i = 0; i < length; ++i)
{
int pos = (p[i] - 97) % 26;
if (unique[pos] != -1)
{
// letter already existed. Start new max
++subSeq;
max[subSeq] = i - unique[pos] - 1;
for (int j = 0; j < unique.size(); ++j)
{
if (unique[j] != -1)
{
unique[j] = unique[pos];
}
}
}
++max[subSeq];
if (max[subSeq] == 26)
{
flag == true;
break;
}
unique[pos] = i;
}
int result = 0;
if (!flag)
{
for (it i = max.begin(); i != max.end(); ++i)
{
if (*i > result)
{
result = *i;
}
}
}
else
{
result = 26;
}
cout << result << endl;
cout.flush();
}
【问题讨论】:
-
我无法理解您的示例。如果
ab在您的示例输入中出现两次,为什么它是一个唯一的子序列?这里的“最大”是什么意思?这表明你想要最长的,但最长的就是输入字符串本身,所以这也不是你想要的。 -
代码是如何测试的?您可以更改
string p = argc > 1 ? argv[1] : "aabbaba";以便能够通过非常简单的输入来测试您的问题 - 那么错误应该很明显 -
@hvd 也许独特这个词具有误导性。在子序列
ab中,所有字母都是唯一的。 -
@User12547645 啊!谢谢,这更有意义。
-
我得到 6。也许你误解了我的改变。
标签: c++ sequence subsequence