본문 바로가기

Interview Preparation Kit/String Manipulation

Sherlock and the Valid String

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  character at  index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid.

For example, if , it is a valid string because frequencies are . So is  because we can remove one  and have  of each character in the remaining string. If  however, the string is not valid as we can only remove  occurrence of . That would leave character frequencies of .

Input Format

A single string .

Constraints

  • Each character 

Output Format

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

Sample Input 0

aabbcd

Sample Output 0

NO

Explanation 0

Given , 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  is invalid.

Sample Input 1

aabbccddeefghi

Sample Output 1

NO

Explanation 1

Frequency counts for the letters are as follows:

{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2, 'f': 1, 'g': 1, 'h': 1, 'i': 1}

There are two ways to make the valid string:

  • Remove  characters with a frequency of .
  • Remove  characters of frequency .

Neither of these is an option.

Sample Input 2

abcdefghhgfedecba

Sample Output 2

YES

Explanation 2

All characters occur twice except for  which occurs  times. We can delete one instance of  to have a valid string.




아!!!! 문제가 쉬운듯 하면서 상당히 까다롭다!

이것저것 따져야 할 것이 많다.!

앞문자, 앞앞문자의 연속성 체크!!!

Discussion에는 대부분 JAVA의 얘기만 가득한데......Github의 c++ 풀이를 보면서 로직을 이해해봤다.

처음 내가 작성한 코드는 Run Code는 넘어가지만, 테스트 케이스를 넘어가지 못한다. 뭔가 머리로의 이해의 한계에 왔다고나 할까. ㅠ

정말 Medium 레벨의 문제들은 은근 까다롭고 생각을 오래 할 수록 더 꼬여만 간다.


내가 작성한 코드다. (실패코드)



이게 성공한 코드이다.



'Interview Preparation Kit > String Manipulation' 카테고리의 다른 글

Common Child  (0) 2018.08.02
Special Palindrome Again  (0) 2018.07.26
Alternating Characters  (0) 2018.07.25
Making Anagrams  (0) 2018.07.25