Leetcode (6) Z 자형 변환
[주제 표현]
아래에 주어진 행에있어서 소정의 캐릭터의 수는, 상기 Z 자형 배열의 좌.
실시 예는, 입력 문자열의 행 "LEETCODEISHIRING"의 개수는 다음과 같이 배열, 3 :
L C I R
E T O E S I I G
E D H N
"LCIRETOESIIGEDHN"행 오른쪽으로 읽기 라인 왼쪽에서 그 후, 당신은 같은 새로운 캐릭터를 생성, 출력이 필요합니다.
첫째, 법에 따라 표준 출력 행을 찾습니다
실행시 : 84 MS, 메모리 소비량 : 11.8MB 효과 : OK
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
res=""
List=[]
#一组是2*numRows-2个
#len(s)<numRows
s_number,Aqueue=len(s),2*numRows-2
if len(s)==0 or Aqueue==0:
return s
queue_number=s_number/Aqueue
Yushu=s_number-queue_number*Aqueue
for i in range(1,numRows+1):
List.append("")
for j in range(0,queue_number):
if i==1 or i==numRows:
List[i-1]+=s[i+Aqueue*j-1]
else:
List[i-1]+=s[i+Aqueue*j-1]
List[i-1]+=s[i+Aqueue*j-1+(numRows-i)*2]
if Yushu>=i:
List[i-1]+=s[i-1+s_number-Yushu]
if (i+(numRows-i)*2)<=Yushu and i!=numRows:
List[i-1]+=s[i-1+s_number-Yushu+(numRows-i)*2]
res+=List[i-1]
return res
배우기
- 각 행의 목록에 저장된 문자의 출력 문자열을 사용하여, 법을 찾으려면
두 번째 방법 : 라인 출력에서 나는 · Z 문자열
때 실행 : 80 MS] 메모리 소비 : 13.2MB 효과 : 아주 좋은
class Solution:
def convert(self, s: str, numRows: int) -> str:
L = ['' for x in range(numRows)]
n = 0
flag = True
for i in s:
if n > numRows - 2:
flag = False
elif n <= 0:
flag = True
L[n] += i
if flag:
n += 1
else:
n -= 1
return ''.join(L)
배우기
보도 Z 단어는 현재 걷고 있다는 마크 또는 폴드 백으로 커서의 수, 깃발을 그룹으로 이동, n은
내가 생각했던 것보다 더 나은
[ '내지 X (numRows의) 미국]'.join (L)