알고리즘/LeetCode
[LeetCode] Zigzag Conversion (Java)
라이언납시오
2022. 2. 17. 18:38
728x90
반응형
문제 링크: https://leetcode.com/problems/zigzag-conversion/
Zigzag Conversion - 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
1. 주의할 점
- 큰 2차원 배열을 사용하지 않는다(Ex. 1시 방향으로 올라갈때 우측 1칸, 위로 1칸) → 메모리 절약
- numRows의 값에 따라 패턴 길이를 구한다
2. 구현
- String[] 배열에 문자들을 추가하는 방식으로 구현한다
- 몇 개를 기준으로 각 문자열이 패턴을 이루는지 파악한다
- numRows가 1일때를 제외하고 2*(numRows-1) 마다 문자열의 형태가 반복된다
- 내려갈 때와 올라갈 때 각각 어떤 인덱스의 문자열에 추가되는지 계산한다
class Solution {
public String convert(String s, int num) {
if(num==1) return s;
String answer = "";
String[] str= new String[num];
for(int i=0;i<num;i++)
str[i]="";
int mod = 2*num-2;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
int idx = i%mod;
if(idx>=num) idx = 2*(num-1)-idx;
str[idx]+=c;
}
for(int i=0;i<num;i++)
answer += str[i];
return answer;
}
}
728x90
반응형