[Python] 344. Reverse String

2021. 1. 8. 18:50·study/LeetCode
728x90

leetcode.com/problems/reverse-string/

 

Reverse String - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

풀이

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        time = len(s)/2
        count = 0
        while time >= 1 :
            time -= 1
            temp = s[count]
            s[count] = s[-(count+1)]
            s[-(count+1)] = temp
            count += 1
        

투포인터

2개의 포인터를 이용해 범위를 조절해가며 품.

문자열의 시작을 가리키는 left와 문자열의 끝을 가리키는 right를 선언.

left가 right보다 왼쪽에 있는 동안 left 위치의 내용과 right위치의 내용을 바꿈

def reverseString(self, s: List[str]) -> None:
	left, right = 0, len(s) -1
    while left < right
    	s[left], s[right] = s[right], s[left]
        left +=1
        right -=1

 

 

reverse()

리스트에 제공되는 메소드로 문자열을 거꾸로 뒤집음.

list = [0,1,2,3]
list.reverse()

print(list)
# [3,2,1,0]

 

reversed()

리스트에 제공되는 메소드로 순서가 거꾸로 뒤집힌 리스트를 반환함

list = [0,1,2,3]
print(list.reversed())
# [3,2,1,0]

 


시간을 단축시키기 위해

1. 파이썬의 reverse이용

2. 리스트의 [::-1]이용


처음 생각했던 알고리즘의 문제점(틀린이유)

1. 슬라이싱 개념 부족 

    뒤에서 카운트 할 때 -1부터 시작하는 것을 몰랐음.

    -1인거 알고 슬라이싱 할 때, -count+1을 해서 올바르게 수행이 안됬었음.

    올바르게 수행하기 위해서 -(count+1)로 괄호를 씌워야만 했었음.

 

2. 끝까지 계산 안해서 while 조건문 횟수 틀림

728x90

'study > LeetCode' 카테고리의 다른 글

[Python] 15. Two Sum  (0) 2021.02.17
[Python] 1. Two Sum  (0) 2021.01.22
[Python] 819. Most Common Word  (0) 2021.01.15
[Python] 937. Reorder Log Files  (0) 2021.01.15
[Python] 125. Valid Palindrome  (0) 2021.01.08
'study/LeetCode' 카테고리의 다른 글
  • [Python] 1. Two Sum
  • [Python] 819. Most Common Word
  • [Python] 937. Reorder Log Files
  • [Python] 125. Valid Palindrome
bbooo
bbooo
  • bbooo
    bbooo
    bbooo
  • 전체
    오늘
    어제
    • 분류 전체보기 (142)
      • study (61)
        • 백준(BOJ) (34)
        • Programmers (15)
        • LeetCode (9)
      • AI (4)
        • Paper (0)
      • SSAC X IFFEL (4)
        • DeepML (1)
        • 밑바닥 부터 시작하는 딥러닝 (2)
      • 회고 (46)
      • Error (10)
      • Setting (15)
  • 블로그 메뉴

    • 홈
    • 태그
    • 글쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    항해99
    개발자 취업
    풀이 실패
    docker
    그리디 알고리즘
    Counter
    typeerror: sequence item 0: expected str instance int found
    백준 2470
    브루트포스
    백준
    programmers 석유시추
    vscode
    LeetCode
    투포인터
    파이썬
    두 포인터
    programmers 과제 진행하기
    set
    99클럽
    파이썬 과제 진행하기
    python 과제 진행하기
    sort
    파이썬 석유시추
    문자열을 원하는 길이로
    코딩테스트 준비
    Til
    python 석유시추
    프로그래머스 석유시추
    sequence item 0: expected str instance int found
    백트래킹
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
bbooo
[Python] 344. Reverse String
상단으로

티스토리툴바