String


Reverse

input = list("abcdefg")

mid = int(len(input)/2)
left = 0
right = len(input)-1

while left < right:
    input[left], input[right] = input[right], input[left]
    left += 1
    right -= 1

print(input)

Super Reduced String

  • pair string을 줄이는 작업을 수행 한다.
def super_reduced_string(S):
    LS = list(S)
    i = 0
    while i < len(LS)-1:
        if LS[i]==LS[i+1]:
            del LS[i]
            del LS[i]
            i = 0
            if len(LS) == 0:
                return 'Empty String'
        else:
            i+=1
    return ''.join(LS)

CamelCase

eBay, iPhone처럼 중간에 띄어쓰기 없이 대소문자로만 단어를 구분하는 것을 말한다.

이렇게 표시된 unique한 단어가 몇개인지 찾아서 출력 해야 한다.

#!/bin/python3

import sys
import string

s = input().strip()

sl = list(s)

i = 0
count = 1
while i < len(sl):
    if sl[i].isupper():
        count += 1
    i += 1

print(count)

한줄 코드

print(sum(map(str.isupper, input())) + 1)

Sliding Window

https://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/

Two Characters

번갈아 가면서 두개의 서로다른 character를 배열 해야 한다.

  • (o) xyxyx or yxyxy
  • (x) xxyy or xyyx

들어온 입력에 대해서 가능한한 가장 긴 두개의 charater로만 생성 가능한 그리고 번갈아 가면서(alternating)으로 만들 수 있는 string을 반환하는게 목적이다.

불가능 하다면 0을 리턴 한다.

예제

10
beabeefeab

해설

  • If we delete e and f, the resulting string is babab. This is a valid as there are only two distinct characters (a and b), and they are alternating within the string.
  • If we delete a and f, the resulting string is bebeeeb. This is not a valid string because there are three consecutive e's present.
  • If we delete only e, the resulting string is babfab. This is not a valid string because it contains three distinct characters.
  • Thus, we print the length of babab, which is , as our answer.
import sys

def validate(inp):
    for i in range(len(inp)-1):
        if inp[i+1]==inp[i]:
            return False
    return True    
    

s_len = int(input().strip())
s = input().strip()

ans = 0
chtoindex = []
for ch in set(s):
    chtoindex.append((ch, len([j for j, x in enumerate(s) if x == ch])))
    

for i, pack in enumerate(chtoindex[:-1]):
    char_i, lenchar_i = pack[0], pack[1]
    for j, otherpack in enumerate(chtoindex[i+1:]):
        char_j, lenchar_j = otherpack[0], otherpack[1]
        if abs(lenchar_i-lenchar_j)<2:
            c = [cha for cha in s if cha is char_i or cha is char_j]
            if validate(c):
                ans = max(ans, lenchar_j+lenchar_i)
print(ans)

참고자료

문자열관련 Python 유용함수 모음 블로그


'Computer Science > Coding Interview' 카테고리의 다른 글

Sorting  (0) 2017.08.06
Graph Search  (0) 2017.08.06
HackerRank- Trees: Is This a Binary Search Tree  (0) 2017.07.31
Binary Search Tree  (0) 2017.07.31
HackerRank Queues: A Tale of Two Stacks  (0) 2017.07.30

+ Recent posts