【发布时间】:2013-03-06 02:29:08
【问题描述】:
我正在尝试找到一种最佳方法来查找字符串模式并进行比较。例如,我有 s1 = "red blue blue red red yellow" 和 s2 = "abbaac"。这将匹配,因为它们具有相同的模式。
我的想法是遍历 s1 和 s2,使用向量容器记录对应位置的计数(s1 为对应单词数,s2 为对应字母数),然后进行比较。
这真的很低效,因为我遍历整个 s1 和 s2。如果 s1 = "red blue red red red yellow" and s2 = "abbaac"。在第三个 red 之后,基本上没有必要继续迭代它。
那么,有什么更好的办法吗?
代码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <array>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> findPattern(string pattern){
vector<int> counts;
for (int i = 0; i < pattern.size(); ++i){
counts.push_back(0);
int counter = 0;
for (int j = i + 1; j < pattern.size(); ++j){
if (pattern[i] == pattern[j]){
++counter;
}
counts[i] = counter;
}
}
return counts;
}
vector<int> findPatternLong(string pattern){
istringstream iss (pattern);
string word;
vector<string> v;
while (iss >> word){
v.push_back(word);
}
vector<int> counts2;
for (int i = 0; i < v.size(); ++i){
counts2.push_back(0);
int counter = 0;
for (int j = i + 1; j < v.size(); ++j){
if (v[i] == v[j]){
++counter;
}
counts2[i] = counter;
}
}
return counts2;
}
int main(int argc, char * argv[]){
vector<int> v1 = findPattern("abbaac");
vector<int> v2 = findPatternLong("red blue blue red red yellow");
if (v1.size() == v2.size()){
for (int i = 0; i < v1.size(); ++i){
if (v1[i] != v2[i]){
cout << "Unmatch" << endl;
return false;
}
}
cout << "match" << endl;
return true;
} else
cout << "Unmatch" << endl;
return 0;
}
【问题讨论】:
标签: c++ vector pattern-matching iteration