【问题标题】:Longest substring that occurs at least twice: C++ question至少出现两次的最长子字符串:C++ 问题
【发布时间】:2011-10-02 06:12:10
【问题描述】:

我知道这个标题很糟糕,但在我知道我的问题的答案之前,我想不出更好的答案。如果可以,请编辑。

我在一个 OnlineJudge 网站上解决(为了好玩)一个非常简单的问题。问题是这样的:

输入: 单个字符串,包含 小写拉丁字母。的长度 字符串至少为 1 且最多为 100。
输出: 单个数字,即 的最长子串的长度 至少出现的输入字符串 在该字符串中出现两次(出现可能重叠)。

样本输入: ababa
样本输出: 3

我通过以下代码获得接受

#include <iostream>
#include <string>
#include <algorithm>
int main()
{
    std::string s;
    std::cin >> s;
    int max = 0;
    typedef std::string::const_iterator sit;
    sit end = s.end();
    for(sit it1 = s.begin(); it1 != end; ++it1)
        for(sit it2 = it1 + 1; it2 != end; ++it2)
            max = std::max(max, std::mismatch(it1, it1 + (end - it2), it2).first - it1);
    std::cout << max;
}

但是,我得到 测试 42 上的运行时错误(我不知道那是什么输入 - 站点规则),其代码与以下代码略有不同第一个。

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    string s;
    cin >> s;
    vector<size_t> dif;
    for(string::const_iterator it1 = s.begin(); it1 != s.end(); ++it1)
        for(string::const_iterator it2 = it1 + 1; it2 != s.end(); ++it2)
            dif.push_back(mismatch(it1, it1 + (s.end() - it2), it2).first - it1);
    cout << *max_element(dif.begin(), dif.end());
}

经过半个小时的仪式舞蹈,我放弃了。我不知道第二个代码有什么问题(除了效率稍低且可读性差的事实)。是我从iterator 中减去const_iterator 吗?还是因为 int vs. size_t?代码是用 MSVC8.0 或 9.0 编译的(在他们的网站上)。释放模式。有任何想法吗?谢谢。

【问题讨论】:

  • 你能提供原始问题陈述的链接吗?
  • @MAK:我不明白这与这里有什么关系。也就是说,除非您想用@Armen 的第一个代码获得积分:)
  • @MAK:是俄语的,我已经准确地给出了所有条件
  • @Martinho Fernandes:嗯,首先想到的是输入字符串可以有多长。问题中还可能存在 OP 可能遗漏的其他陷阱。我也很好奇问题出在哪里,因为我也喜欢在各种 OJ 中解决问题。通过提交别人的代码来获得“积分”,你不觉得吗?
  • @yi_H: 如果输入字符串是 100 个字符长,最好编写一个快速的蛮力代码,而不是花时间考虑更好的算法(时间压力,你知道的)

标签: c++ string algorithm stl


【解决方案1】:

如果不运行您的代码,我认为您的第二个解决方案在长度为 1 的输入字符串上失败。

只要输入字符串的长度为 1,您的 dif 向量就为空,这会导致 *max_element(dif.begin(), dif.end()) 失败。

【讨论】:

  • 这会产生访问冲突,在调试模式下运行给出以下描述:表达式:向量迭代器不可解引用
【解决方案2】:

它对长度为 1 的输入产生段错误。

您正在尝试从空向量中取消引用。

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2018-11-06
    • 1970-01-01
    相关资源
    最近更新 更多