为什么我的算法不对呢,ab 可以检测,但超过两个不同的,就不对了
先写在这里,哪天有思路了再看看
// LeetCode.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<map>
#include<unordered_map>
#include<string>
using namespace std;
/**/
class Solution {
public:
bool wordPattern(string pattern, string str) {
int n = 0;
for (int i = 0; i < str.size(); i++)
if (str[i] == ‘ ‘)
n++;
//cout << n << pattern.size();
if (n + 1 != pattern.size())
return false;
unordered_map<string, string> map;
for (int i = 0; i<pattern.size(); ++i)
{
int wei = str.find(" ");
string t = str.substr(0, wei);
str = str.substr(wei + 1);
auto d = map.find(""+pattern[i]);
if (d != map.end() && map["" + pattern[i]] != t)
return false;
else if (d != map.end() && map["" + pattern[i]] == t)
continue;
else if (d == map.end()) {
for (auto k : map)
{
if (k.second == t)
return false;
}
}
map[""+pattern[i]] = t;
}
return true;
}
};
void print(string str) {
for (int i = 0; i < 4; ++i)
{
string t = str.substr(0, str.find(" "));
int wei = str.find(" ");
str = str.substr(wei + 1);
cout << t << endl;
}
}
int main()
{
Solution s;
if (s.wordPattern("abbbac", "aa bb bb bb aa cc" ))
cout << "ok";
// print("aa dd kk ss");
system("pause");
return 0;
}
把map<string,string> 改成 map<char,string> 然后把""+去掉,就可以了,为什么呢?运行时间0ms 开心,但为什么string 就有问题呢?
跟map 有关系吧
原文:http://www.cnblogs.com/yanqi110/p/4990464.html