-
[LeetCode] 290. Word PatternLeetCode 2022. 1. 17. 10:45728x90
https://leetcode.com/problems/word-pattern/
Word Pattern - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Word Pattern - Easy

pattern과 s가 주어진다.
s를 띄어쓰기 기준으로 자른 단어들과
pattern에 있는 각각의 알파벳이 1대1로 대응하는지 판단하는 문제다.
먼저 map m,m2를 만든다. 이는 패턴-단어와 단어-패턴을 매핑한다.
pattern을 쭉 훑으며 동시에 띄어쓰기 기준으로 잘린 s의 단어들을 훑는다.
m[pattern]이 비어있고, m2[word]가 비어있다면, m[pattern] = word, m2[word] = pattern으로 매핑하고,
비어있지 않다면 둘을 비교해 같다면 다음으로, 같지 않다면 바로 false를 리턴한다.
마지막으로 pattern과 s가 끝까지 훑어졌는지 확인해주자.
전체 풀이 코드
class Solution { public: bool wordPattern(string pattern, string s) { unordered_map<char, string> m; unordered_map<string, char> m2; int i=0, j=0; for (; i<pattern.length(); i++,j++) { string word=""; while(s[j]!=' ' && j<s.length()) word = word + s[j++]; if (m[pattern[i]]=="" && m2[word]=='\0') { m[pattern[i]] = word; m2[word] = pattern[i]; } else if (m[pattern[i]]==word) continue; else return false; } return i==pattern.length() && j==s.length()+1; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 875. Koko Eating Bananas (0) 2022.01.20 [LeetCode] 605. Can Place Flowers (0) 2022.01.18 [LeetCode] 452. Minimum Number of Arrows to Burst Balloons (0) 2022.01.13 [LeetCode] 701. Insert into a Binary Search Tree (0) 2022.01.12 [LeetCode] 1041. Robot Bounded In Circle (0) 2022.01.09