c++ - fast way for string comparison -
i have simple question makes me confused.
i have 2 strings, , want count how many different characters between two. strings sorted, equal length. not split strings.
for example
input: abc, bcd output: 2, because , d different characters input: abce, bccd output: 4, because a, c, d , e different.
i know can in o(n^2), how can solve in o(n) these sorted strings?
only need number of different characters, no need indicate number.
i thinking needed complicated algorithm, smith-waterman example. restrictions on input makes easy implement in o(m + n)
, m
length of first string, , n
length of second string.
we can use builtin algorithm calculate number of characters in common, , can use information produce number looking for:
#include <algorithm> #include <iostream> #include <string> int main() { std::string m = "abce"; std::string n = "bccd"; std::string result; std::set_intersection( m.begin(), m.end(), n.begin(), n.end(), std::back_inserter(result)); std::cout << m.size() + n.size() - 2 * result.size() << "\n"; }
in particular case, outputs 4
, wanted.
Comments
Post a Comment