관리 메뉴

솜씨좋은장씨

[HackerRank] Dictionaries and Hashmaps: Two Strings (Python) 본문

Programming/코딩 1일 1문제

[HackerRank] Dictionaries and Hashmaps: Two Strings (Python)

솜씨좋은장씨 2020. 3. 14. 01:29
728x90
반응형

Given two strings, determine if they share a common substring. A substring may be as small as one character.

For example, the words "a", "and", "art" share the common substring a. The words "be" and "cat" do not share a substring.

Function Description

Complete the function twoStrings in the editor below. It should return a string, either YES or NO based on whether the strings share a common substring.

twoStrings has the following parameter(s):

  • s1, s2: two strings to analyze .

Input Format

The first line contains a single integer p, the number of test cases.

The following p pairs of lines are as follows:

  • The first line contains string s1.
  • The second line contains string s2.

Constraints

  • s1 and s2 consist of characters in the range ascii[a-z].
  • 1 <= p <= 10
  • 1 <= | s1 |, | s2 | <= 10^5

Output Format

For each pair of strings, return YES or NO.

 

Sample Input

2
hello
world
hi
world

Sample Output

YES
NO

Explanation

We have p = 2 pairs to check:

  1. s1 = "hello", s2 = "world". The substrings "o" and "1" are common to both strings.
  2. a = "hi", b = "world". s1 and s2 share no common substrings.

Solution

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the twoStrings function below.
def twoStrings(s1, s2):
    answer = "NO"
    s1_set = set(list(s1))
    s2_set = set(list(s2))

    intersection = s1_set.intersection(s2_set)

    if len(intersection) != 0:
        answer = "YES"

    return answer

Solution 풀이

set에서 교집합을 구해주는 intersection메소드를 활용하여

교집합 결과가 비었으면 "NO" 그렇지 않으면 "YES" 를 return하도록 합니다.

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments