开发者

Longest substring that occurs at least twice: C++ question

The title is horrible, I know, but until I know the answer to my question, I can't think of a better one. If you can, please edit.

I was solving (for fun) a very easy problem on one of OnlineJudge sites. The problem is this:

Input: a single string containing lowercase latin letters. The length of string is at least 1 and at most 100.

Output: a single number which is the length of the longest substring of the input string which occurs at least twice in that string( the occurrences may overlap).

Sample input: ababa

Sample output: 3

I got Accepted with the following code:

#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;
}

However, I get Runtime Error on Test 42 (I can't know what input is that - site rules) with the following code which is but slightly different from the first one.

#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());
}

After half an hour of ritual dancing, I give up. I can't figure out what's wrong with the second code (except the fact that is's slightly less effective and less readable). Is it that I am substracting a const_iterator from an iterator? Or because of int vs. si开发者_Python百科ze_t? The code is compiled (on their site) with MSVC8.0 or 9.0. Release mode. Any ideas? Thanks.


Without running your code, I think your second solution fails on input strings of length 1.

Your dif vector is empty whenever the input string has length 1, which causes *max_element(dif.begin(), dif.end()) to fail.


It segfaults on an input with length 1.

You are trying to derefence from an empty vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜