saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 딕셔너리
  • LeetCode
  • 알고리즘
  • 알고리즘문제해결
  • Python
  • 백준
  • two pointer
  • 딥러닝
  • 문제해결능력
  • 취준
  • c++
  • BFS
  • 개발자 취업준비
  • 온라인저지
  • 개발자
  • 취업준비
  • 리트코드
  • DFS
  • 릿코드
  • 파이썬

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 990. Satisfiability of Equality Equations

2022. 9. 26. 14:49

990. Satisfiability of Equality Equations

Medium

You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.

 

Example 1:

Input: equations = ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.

Example 2:

Input: equations = ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

 

Constraints:

  • 1 <= equations.length <= 500
  • equations[i].length == 4
  • equations[i][0] is a lowercase letter.
  • equations[i][1] is either '=' or '!'.
  • equations[i][2] is '='.
  • equations[i][3] is a lowercase letter.

문제 풀이

  1. a==b 와 같은 식이 주어진다.
  2. 변수 사이에 들어가는 조건식은 != 혹은 == 이다. 
  3. 즉 주어지는 모든 식들의 조건이 맞아야한다. 
  4. 예를 들어 a==b, a!=b 가 주어진다면, 답은 False 이다. 
  5. 반대로 a==b, b==a 이면 답은 True 이다. 
  6. 여기서 a==b, b==c, a!=c 는 성립되지 않는다, 왜냐하면 a==b==c 인 상황에서 a==c 이기 때문이다.
  7. 이를 고려할때, 그룹을 지어줘야하는 Union-Find 알고리즘을 사용할 수 있어 보인다. 
  8. DFS, BFS 혹은 재귀함수로 풀수도 있겠지만, 소스코드가 더 복잡해질 수 있다.
  9. a==b, b==c, a!=c 조건을 보면, a==b==c 인 상태는 결국 a, b, c 는 모두 같은 그룹에 있다고 생각할 수 있다.

소스 코드

class Solution:
    def equationsPossible(self, equations: List[str]) -> bool:
        hashTable = defaultdict()
        candidates = []
        def find(a, hashTable):
            if a == hashTable[a]:
                return a
            hashTable[a] = find(hashTable[a], hashTable)
            return hashTable[a]
        
        def union(a, b, hashTable):
            a_p = find(a, hashTable)
            b_p = find(b, hashTable)
            
            if a_p != b_p:
                hashTable[a_p] = b_p
        
        for i in range(ord('a'), ord('z') + 1):
            hashTable[chr(i)] = chr(i)
        
        for s in equations:
            a1 = s[0]
            a2 = s[3]
            if s[1] == '=':
                union(a1, a2, hashTable)
            else:
                candidates.append((a1, a2))
        
        for a, b in candidates:
            if find(a, hashTable) == find(b, hashTable):
                return False
        return True
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 985. Sum of Even Numbers After Queries  (0) 2022.09.27
[LeetCode] 298. Binary Tree Longest Consecutive Sequence  (0) 2022.09.27
[LeetCode] 159. Longest Substring with At Most Two Distinct Characters  (1) 2022.09.24
[LeetCode] 1680. Concatenation of Consecutive Binary Numbers  (0) 2022.09.24
[LeetCode] 1272. Remove Interval  (1) 2022.09.23
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 985. Sum of Even Numbers After Queries
    • [LeetCode] 298. Binary Tree Longest Consecutive Sequence
    • [LeetCode] 159. Longest Substring with At Most Two Distinct Characters
    • [LeetCode] 1680. Concatenation of Consecutive Binary Numbers
    saurus2
    saurus2
    Simple is Best

    티스토리툴바