The HackerRank Interview Preparation Kit

Sherlock and the Valid String 해석 및 풀이

기억속산책 2020. 3. 8. 21:55

문제 : https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings

 

Sherlock and the Valid String | HackerRank

Remove some characters from the string such that the new string's characters have the same frequency.

www.hackerrank.com

 

원문 : 

Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just 1 character at 1 index in the string s, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return YES, otherwise return NO.

 

For example, if s = abc, it is a valid string because frequencies are {a:1, b:1, c:1} . So is s=abcc because we can remove one c and have 1 of each character in the remaining string. If s = abccc however, the string is not valid as we can only remove 1 occurrence of c. That would leave character frequencies of {a:1,b:1,c:2}.

 

Function Description

Complete the isValid function in the editor below. It should return either the string YES or the string NO.

isValid has the following parameter(s):

s: a string

 

Output Format

Print YES if string s is valid, otherwise, print NO.

 

Explanation 0

Given s = "aabbcd", we would need to remove two characters, both c and d --> aabb or a and b --> abcd, to make it valid. We are limited to removing only one character, so s is invalid.

 

해석 :

문자열의 모든 문자가 동일한 횟수로 표시되면 Sherlock은 문자열이 유효한 것으로 간주합니다. 문자열 s 에서 1개의 인덱스인 1개의 문자를 삭제하는 것 또한 유효한 것으로 간주 합니다.  나머지 문자는 같은 횟수로 발생합니다. 문자열 s가 주어지고 그것이 유효한지 결정하세요. 맞으면 YES 를 틀리면 NO를 리턴합니다. 

 

예를 들어 s =abs 이면 각문자의 횟수는 {a:1, b:1, c:1} 로 유효한 것입니다.s = abcc 는 c하나를 없앨 수 있기때문에 각 1개씩 문자가 남기떄문에 유효합니다. 그러나 만약 s = abccc 이면 우리는 c 1개의 문자만 삭제 할 수 있기 때문에 횟수가 {a:1,b:1,c:2} 가 되므로 유효하지 않습니다. 

 

기능 설명 

아래의 에디터에서 isValid 기능을 완성하세요. 그것은 문자열 YES나 NO를 리턴하여여 합니다. 

isValid 는 다음과 같은 파라미터를 가지고있습니다. 

s : 문자열

 

출력 형태 

만약 문자열 s가 유효하면 YES 아니면 NO를 출력하세요.

 

설명 0

주어진 문자열 aabbcd 를 유효하게 만드려면 두개를 삭제하여야 합니다. c나 d 를 삭제하면 aabb, a나 b 한개면 abcd 

우리는 오직 한개의 문자만 삭제 할수있도록 되어있기 떄문에 s는 유효하지 않습니다.

 

 

해답 : https://github.com/lorh2700/algo/tree/master/bjtest/src/HakerRank/SherlockAndTheValidString

 

 

팁 : 

1. 알파벳 소문자만 있다. 

2. 각 알파벳의 갯수만 알고있으면 된다.