In [35]:
def isUniqChars(str) :
# 각 문자가 ASCII라고 가정(총 256개)
# 맨약 문자열이 256보다 길면 중복이 있다.
if len(str) > 256 :
return False
# boolean 배열 초기화
hash = [False] * 256
for ch in str :
# boolean 배열이 True이면 중복이 있음
if hash[ord(ch)] is True : ## ord함수는 문자를 ascii코드로 변환하는 함수
return False
# boolean 배열이 False이면 아직 중복이 없음
else :
hash[ord(ch)] = True
return True
In [36]:
def my_isUniqChars(str) :
# set함수를 이용하여 중복된 문자를 제거한 후 길이를 비교하여 길이가 달라지면 False
return len(set(str)) == len(str)
In [39]:
print(isUniqChars('abcdea'), my_isUniqChars('abcdea'),
isUniqChars('abecspi'), my_isUniqChars('abecspi'))
In [3]:
def reverseString2(str) :
stack = []
for ch in str :
stack.append(ch)
result = ""
while len(stack) > 0 :
result += stack.pop()
return result
In [7]:
def my_reverseString2(str) :
stack = [ch for ch in str]
result = [stack.pop() for _ in range(len(str))]
return ''.join(result)
In [40]:
print(reverseString2('abcde'), my_reverseString2('abcde'),
reverseString2('가나다라'), my_reverseString2('가나다라'))
In [9]:
def anagram(str1, str2) :
if ''.join(sorted(str1.lower())).strip() == ''.join(sorted(str2.lower())).strip() :
return True
else :
return False
In [42]:
print(anagram('LISTEN', 'SILENT'), anagram('LIsTEN', 'SILeNT'), anagram('LIsT EN', 'SILe NT'))
In [10]:
def replace_space(str) :
return str.strip().replace(' ', '%20')
In [43]:
replace_space('Mr John Smith ')
Out[43]:
In [56]:
def compressword(input) :
buffer = None
output = ''
cnt = 1
for ch in input :
if buffer is None :
output += ch
buffer = ch
else :
if buffer == ch :
cnt += 1
else :
output += str(cnt)
cnt = 1
output += ch
buffer = ch
output += str(cnt)
if len(output) > len(input) :
return input
else :
return output
In [57]:
def my_compressword(input) :
idx = 0
count = 1
result = []
for ch in input[1:] :
if ch == input[idx] :
count += 1
else :
result.extend([input[idx], str(count)])
count = 1
idx += 1
result.extend([input[idx], str(count)])
if len(result) > len(input) :
return input
return ''.join(result)
In [58]:
print(compressword('aabccccaa'), my_compressword('aabccccaa'),
compressword('ssseiiaaddddd'), my_compressword('ssseiiaaddddd'))