[Leetcode] 6. Zigzag Conversion
2024. 3. 8. 23:07ㆍTech: Algorithm
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
line별로 문자열을 넣어두는 list를 만드는데, 만드는 방법은 맨 밑과 윗줄에 닿았을때만 방향을 바꿔주면 되는데 방향을 바꾼다는 의미가 currentLine을 더하거나 빼거나를 정해준다는 뜻.
if 맨 윗줄이거나 맨 아래에 닿으면 -> 방향부호를 정함
아래로 내려가면 -> line ++
위로 올라가면 -> line --
class Solution {
public:
string convert(string s, int numRows) {
if(numRows<=1) return s;
string ret="";
vector<string> list(numRows, "");
int currentLine = 0;
bool reachedEdge = true;
for (int i = 0; i < s.length(); ++i) {
if (currentLine == 0 || currentLine == numRows - 1) {
reachedEdge = !reachedEdge;
}
list.at(currentLine) += s.at(i);
if (!reachedEdge) {
currentLine++;
} else {
currentLine--;
}
}
for(int i=0;i<numRows;i++)
ret+=list.at(i);
return ret;
}
};
'Tech: Algorithm' 카테고리의 다른 글
[Leetcode] 8. String to Integer (atoi) (0) | 2024.03.12 |
---|---|
[Leetcode] 7. Reverse Integer (0) | 2024.03.11 |
[Leetcode] 5. Longest Palindromic Substring (0) | 2024.03.07 |
[Leetcode] 4. Median of Two Sorted Arrays (3) | 2024.03.06 |
[Leetcode] 3. Longest Substring Without Repeating Characters (2) | 2024.02.27 |