happy318
팽도리블로그
happy318
전체 방문자
오늘
어제
  • 전체글 (252)
    • 공부 (5)
      • Algorithm 정리 (0)
      • 논문리뷰 (1)
      • C++ (2)
      • Python (2)
      • Java (0)
      • Back-end (0)
      • Front-end (0)
      • Embedded (0)
    • 코딩테스트 (218)
      • Python 문제풀이 (100)
      • C++ 문제풀이 (108)
      • Python template (9)
      • C++ template (1)
    • 일상 (20)
      • 맛집 (13)
      • 쇼핑 (5)
      • 아무 일상 (2)
    • 게임 (9)
      • 메이플스토리 (9)

최근 글

인기 글

hELLO · Designed By 정상우.
happy318

팽도리블로그

코딩테스트/C++ 문제풀이

[LeetCode] Zigzag Conversion

2023. 3. 21. 23:17

https://leetcode.com/problems/zigzag-conversion/

 

Zigzag Conversion - LeetCode

Can you solve this real interview question? Zigzag Conversion - 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

leetcode.com

우선 문제부터 간단하게 요약하면, 

 

주어진 string을 주어진 row 수만큼의 범위 내에서 지그재그로 배열을 할 때, 

이렇게 배열된 것을 row기준으로 출력하는 것이 문제입니다. 

 

간단한 예시로 

"PAYPALISHIRING" 라는 string과 3이라는 row가 주어지면,

다음과 같이 배열이 되게 되고, 

이것을 row기준으로 출력하게 되면, "PAHNAPLSIIGYIR"로 읽어지는 것입니다.

 

<Solution>

각 row에 들어오는 문자열을 저장할 vector를 구성해 두고, 주어진 문자열을 쭉 순회하면서 올바른 row에 해당하는 vector에 추가하는 형태로 구현하면 됩니다.

 

이렇게 하면 O(n) (n = 문자열의 길이) 의 시간복잡도 내에 문제를 해결할 수 있습니다. 

 

실제 구현은 아래와 같습니다.

class Solution {
public:
    string convert(string s, int numRows) {
        string returnString;
        vector<string>stringVector(numRows, "");
        
        if(numRows == 1) return s;

        int rowDir = -1, curRow = 0;

        for(int i = 0; i<s.length(); i++){
            if(curRow == 0 || curRow == numRows-1) rowDir*=(-1);

            stringVector[curRow] += s[i];
            curRow += rowDir;
        }

        for(auto &k : stringVector){
            returnString += k;
        }
        return returnString;
    }

};
반응형

'코딩테스트 > C++ 문제풀이' 카테고리의 다른 글

[백준] 단어 수학  (0) 2023.03.26
[백준] 부등호  (2) 2023.03.26
[LeetCode] Path Sum II  (0) 2023.03.21
[백준] 3의 배수  (0) 2023.03.20
[백준] 줄 세우기  (0) 2023.03.12
    '코딩테스트/C++ 문제풀이' 카테고리의 다른 글
    • [백준] 단어 수학
    • [백준] 부등호
    • [LeetCode] Path Sum II
    • [백준] 3의 배수
    happy318
    happy318

    티스토리툴바