c·c++/c++ 프로그래밍

longest common substring

바로이순간 2014. 3. 31. 18:33

#include <iostream>

#include <string>

using namespace std; 

 

int LongestCommonSubstring(const string& str1, const string& str2) {

    if(str1.empty() || str2.empty()) {

        return 0;

    }

 

    int *curr = new int [str2.size()];

    int *prev = new int [str2.size()];

    int *swap = nullptr;

    int maxSubstr = 0;

 

    for(int i = 0; i<str1.size(); ++i) {

        for(int j = 0; j<str2.size(); ++j) {

            if(str1[i] != str2[j]) {

                curr[j] = 0;

            } else {

                if(i == 0 || j == 0) {

                    curr[j] = 1;

                } else {

                    curr[j] = 1 + prev[j-1];

                }

                //The next if can be replaced with:

                //maxSubstr = max(maxSubstr, curr[j]);

                //(You need algorithm.h library for using max())

                if(maxSubstr < curr[j]) {

                    maxSubstr = curr[j];

                }

            }

        }

        swap=curr;

        curr=prev;

        prev=swap;

    }

    delete [] curr;

    delete [] prev;

    return maxSubstr;

}


int main() {

    return 0;

}


http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring


'c·c++ > c++ 프로그래밍' 카테고리의 다른 글

Fraction Class  (0) 2014.05.12
bool 형에 대해서  (0) 2014.04.02
파일의 글자수 세기  (0) 2013.11.09
zigzag  (0) 2013.10.22
최대공약수 구하기  (0) 2013.10.05