Game Development
LeetCode 6번 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
문제
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"
풀이
해당 문제는 주여진 문자열을 지그재리로 배열한 후 출력하시면 됩니다.
Input: s = "ac"
Output: "a"
class Solution {
public:
string convert(string s, int numRows)
{
vector<string> zigzag(numRows);
string answer = "";
bool isDown = true;
for (int i = 0, j = 0; i < s.size(); i++)
{
zigzag[j] += s[i];
if (numRows > 1)
{
if (i != 0 && i % (numRows - 1) == 0)
{
isDown = !isDown;
}
j += (isDown == true ? 1 : -1);
}
}
for (int i = 0; i < numRows; i++)
{
answer += zigzag[i];
}
return answer;
}
};
Time Submitted | Status | RunTime | Memory |
08/03/2021 23:14 | Accepted | 4 ms | 10.8 MB |
시간 복잡도 : O(N^2)
'Algorithms > Leet Code' 카테고리의 다른 글
LeetCode 4번 Median of Two Sorted Arrays (0) | 2023.09.23 |
---|---|
LeetCode 5번 Longest Palindromic Substring (0) | 2021.07.25 |
LeetCode 3번 Longest Substring Without Repeating Characters (0) | 2021.07.25 |
LeetCode 2번 Add Two Numbers (0) | 2021.07.25 |
LeetCode 1번 Two Sum (0) | 2021.07.25 |
Comments