Programming/LeetCode

[Dart] 6. Zigzag Conversion

Meezzi 2025. 5. 9. 12:27
728x90

1. 문제

https://leetcode.com/problems/zigzag-conversion/description/?envType=study-plan-v2&envId=top-interview-150

 

 

 

2. 요구사항

1) 주어진 문자열 s를 numRows개의 행으로 지그재그 패턴으로 배치한 후, 행 순서대로 문자열을 읽어 변환 결과를 반환한다.

s = "PAYPALISHIRING"와 numRows = 3이 주어지면 아래와 같이 배치된다.

P   A   H   N
A P L S I I G
Y   I   R

결과 문자열은 "PAHNAPLSIIGYIR"이 된다.

 

 

 

3. 코드

class Solution {
  String convert(String s, int numRows) {
    if (numRows == 1) return s;

    List<StringBuffer> rows = List.generate(numRows, (index) => StringBuffer());

    int currentRow = 0;       // 현재 작성 중인 행 번호
    bool goingDown = false;   // 아래 방향으로 진행 중인지 여부

    for (int i = 0; i < s.length; i++) {
        // 현재 행에 문자 추가
        rows[currentRow].write(s[i]);

        // 첫 번째 행이나 마지막 행에 도달하면 방향 전환
        if (currentRow == 0 || currentRow == numRows - 1) {
            goingDown = !goingDown;
        }

        // 방향에 따라 현재 행 번호를 증가 또는 감소
        currentRow += goingDown ? 1 : -1;
    }

    // 각 행의 StringBuffer를 문자열로 변환하고 합쳐서 반환
    return rows.join('');
  }
}
728x90