lineEncoding

koeyhoyh·2021년 12월 14일
0

Given a string, return its encoding defined as follows:

First, the string is divided into the least possible number of disjoint substrings consisting of identical characters
for example, "aabbbc" is divided into ["aa", "bbb", "c"]
Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character
for example, substring "bbb" is replaced by "3b"
Finally, all the new strings are concatenated together in the same order and a new string is returned.


Example

For s = "aabbbc", the output should be
solution(s) = "2a3bc".


Input/Output

[execution time limit] 4 seconds (py3)

[input] string s

String consisting of lowercase English letters.

Guaranteed constraints:
4 ≤ s.length ≤ 15.

[output] string

Encoded version of s.


st = "aabbccaabbcc" -> return "2a2b2c2a2b2c"
이렇게 해당 문자의 개수를 파악해 반복된 문자 대신 숫자로 대체하는 문제이다.


Solution

내 해결 코드 :

def solution(s):
    
    myArr = list()
    comp = s[0]
    cnt = 0
    for i in range (1, (len(s[1:]) + 1)) :

        if s[i] == comp :
            continue
            
        else :
            comp = s[i]
            myArr.append(s[cnt:i])
            cnt = i
        
    myArr.append(s[cnt:])
    
    mySt = ""
    for el in myArr:
        if len(el) == 1 :
            mySt += el
        else :
            mySt += str(len(el)) + el[0]
            
    return mySt

아직도 python의 장점을 살리지 못하고 있다...
프로그래머스 "파이썬을 파이썬답게" 강의가 도움이 많이 되고 있다.

best codes :

from itertools import groupby
def solution(s):
    x = ''
    for k,g in groupby(s):
        y = len((list(g)))
        if y==1:
            x += k
        else:
            x += str(y) + k
    return x

itertools 의 groupby 를 사용했다.
groupby는 해당 키로 묶어준 그룹을 만들어준다.

-> k(ey) , g(roup) 의 그룹이 나오는데

g 의 개수를 세어
1개라면 k만,
여러 개라면 개수와 키를 string에 더해서 return 해준다.

간결하고 깔끔하다고 생각한다.

참고 itertools - groupby : https://wikidocs.net/108940

profile
내가 만들어낸 것들로 세계에 많은 가치를 창출해내고 싶어요.

0개의 댓글