Leet - 6

Having fun on Leetcode with C++, Java, Python & GO

Problem 6. Zigzag Conversion

My attempt(s)

Code

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
    string convert(string s, int numRows) {
        int cnt = (numRows - 1) * 2;
	int cntt = 1;
	int cnttt = 0;
	int times = 0;
	int timess = 0; 
	bool last = false;
	std::string ss = "";
    if (numRows==1)
        return s;
	while (ss.length() != s.length()) {
		while (cntt <= s.length()) {
			
			if (cntt == numRows)
				last = true;
			if (!((last) and (timess>0)))
				ss = std::string(ss) + s[cntt - 1];
			if ((cnttt != 0) and (cntt + cnttt <= s.length()) and ((times!=0) or (last))) {
				ss = std::string(ss) + s[cntt + cnttt-1];
				cntt = cntt;
			}
			else if ((cntt + cnttt > s.length()) and (last)) {
				break;
			}
			if ((times != 0) or (last)) {
				timess = timess + 1;
				cntt = cntt + cnttt;

			}
				
			times = times + 1;
			cntt = cntt + cnt;

	
			if (ss.length() == s.length())
				break;
		}
		
		
		cntt = cntt - times * cnt - timess * cnttt + 1;
		times = 0;
		timess = 0;
		cnt = cnt - 2;
		cnttt = cnttt + 2;
	}
	return ss;
    }
};

Explanation of idea

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0