[InterviewBit] Zigzag String

Zigzag String

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string Solution::convert(string A, int B) {
if(B == 1) return A;
int left = (B - 1) * 2, right = 0;
string res = "";
for(int i = 0; i < B; i++,left -= 2, right += 2) {
bool fl = true;
int j = i;
while(j < A.length()) {
res.push_back(A[j]);
if(left == 0 or right == 0) j += (B - 1) * 2;
else if(fl) j += left;
else j += right;
fl = !fl;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/28/PS/interviewbit/zigzag-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.