[LeetCode] 6. Zigzag Conversion (Java)
2023. 1. 2. 07:40ㆍ알고리즘/LeetCode
Description
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
주어진 숫자의 행으로 이루어진 패턴이 어떤 순서로 문자를 바꾸는지 구하라.
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
- 1 <= s.length <= 1000
- s consists of English letters (lower-case and upper-case), ',' and '.'.
- 1 <= numRows <= 1000
Solution
class Solution {
public String convert(String s, int numRows) {
if(numRows==s.length()||numRows==1){
return s;
}
int check=2*numRows-2;
String answer = "";
String[] str = new String[numRows];
for(int i=0;i<numRows;i++){
str[i]="";
}
for(int i=0;i<s.length();i++){
String a = String.valueOf(s.charAt(i));
int at = i%check ;
if(at>=numRows){
at = check-at;
}
str[at] += a;
}
for(int i=0;i<numRows;i++){
answer += str[i];
}
return answer;
}
}
check는 다시 첫번째 줄에 문자가 쓰이는 간격 (numRows=4 이면 paypal 6자) 으로 두고 배열 str에 각 줄의 문자를 입력하였다.
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 8. String to Integer (atoi) (Java) (0) | 2023.01.03 |
---|---|
[LeetCode] 7. Reverse Integer (Java) (0) | 2023.01.02 |
[LeetCode] 5. Longest Palindromic Substring (Java) (0) | 2023.01.02 |
[LeetCode] 4. Median of Two Sorted Arrays (Java) - O(log (m+n)) (0) | 2023.01.02 |
[LeetCode] 4. Median of Two Sorted Arrays (Java) (0) | 2022.12.30 |