https://leetcode.com/problems/word-pattern/
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
arg 로 들어온 string 둘의 패턴을 숫자로 표현해서 저장한다. 그리고 같은지 확인하고 return.
class Solution {
public:
bool wordPattern(string pattern, string s) {
std::unordered_map<char, int> un_map1;
std::unordered_map<string, int> un_map2;
string pattern_toi;
string s_toi;
int val = 1;
for (int i = 0; i < pattern.size(); ++i)
{
if (un_map1[pattern[i]] == 0)
{
un_map1[pattern[i]] = val;
val++;
}
pattern_toi += to_string(un_map1[pattern[i]]);
}
val = 1;
for (int i = 0; i < s.size(); i++)
{
string temp;
while (s[i] != ' ' && i < s.size())
{
temp += s[i];
i++;
}
if (un_map2[temp] == 0)
{
un_map2[temp] = val;
val++;
}
s_toi += to_string(un_map2[temp]);
}
return pattern_toi == s_toi;
}
};
untime: 4 ms, faster than 15.56% of C++ online submissions for Word Pattern.
Memory Usage: 6.5 MB, less than 86.71% of C++ online submissions for Word Pattern.
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Word Pattern.
Memory Usage: 6.5 MB, less than 76.20% of C++ online submissions for Word Pattern.
극단적으로 나뉘네.
다르게 풀어봤다. u_set을 사용해서 a - dog , b - dog 처럼 pattern이 다른데 s 가 같은 값을
걸러냈다.
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
class Solution {
public:
bool wordPattern(string pattern, string s) {
std::unordered_map<char, string> un_map1;
std::unordered_set<string> uset;
string name;
int idx = 0;
int size = s.size();
for (int i = 0; i < pattern.size(); ++i)
{
if (un_map1.find(pattern[i]) != un_map1.end())
{
name = "";
while (!iswspace(s[idx]) && idx < size)
{
name.push_back(s[idx++]);
}
idx++;
if (un_map1[pattern[i]] != name)
return false;
}
else
{
name = "";
while (!iswspace(s[idx]) && idx < size)
{
name.push_back(s[idx++]);
}
//set 은 값이 중복되는지 찾는다.
if (uset.find(name) != uset.end())
{
return false; // else문은 unmap에 값이 없는 경우 들어오게 되는데 set에서
// 같은 값을 찾았다는 것은 중복되었다는 의미가 된다.
}
else
{
uset.emplace(name);
}
idx++;
un_map1[pattern[i]] = name;
}
}
if(idx != size + 1) return false;
return true;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Word Pattern.
Memory Usage: 6.4 MB, less than 76.35% of C++ online submissions for Word Pattern.