Skip to content

Commit 64b603d

Browse files
authored
Update readme with Zigzag Conversion solution
Added detailed explanation and implementation for Zigzag Conversion problem.
1 parent 6927485 commit 64b603d

File tree

1 file changed

+69
-1
lines changed
  • src/main/java/g0001_0100/s0006_zigzag_conversion

1 file changed

+69
-1
lines changed

src/main/java/g0001_0100/s0006_zigzag_conversion/readme.md

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,72 @@ string convert(string s, int numRows);
3636

3737
* `1 <= s.length <= 1000`
3838
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
39-
* `1 <= numRows <= 1000`
39+
* `1 <= numRows <= 1000`
40+
41+
To solve the Zigzag Conversion problem in Java using a `Solution` class, we'll follow these steps:
42+
43+
1. Define a `Solution` class with a method named `convert`.
44+
2. Create an array of strings to represent each row of the zigzag pattern.
45+
3. Initialize variables to keep track of the current row (`row`) and the direction of traversal (`down`).
46+
4. Iterate through each character in the input string `s`.
47+
- Append the current character to the string representing the current row.
48+
- If we reach the first or last row, change the direction of traversal accordingly.
49+
- Update the current row based on the direction of traversal.
50+
5. Concatenate the strings representing each row to form the final zigzag conversion.
51+
6. Return the concatenated string.
52+
7. Handle edge cases where the number of rows is 1 or the input string is empty.
53+
54+
Here's the implementation:
55+
56+
```java
57+
public class Solution {
58+
59+
public String convert(String s, int numRows) {
60+
if (numRows == 1 || s.length() <= numRows) {
61+
return s;
62+
}
63+
64+
StringBuilder[] rows = new StringBuilder[numRows];
65+
for (int i = 0; i < numRows; i++) {
66+
rows[i] = new StringBuilder();
67+
}
68+
69+
int row = 0;
70+
boolean down = false;
71+
72+
for (char c : s.toCharArray()) {
73+
rows[row].append(c);
74+
if (row == 0 || row == numRows - 1) {
75+
down = !down;
76+
}
77+
row += down ? 1 : -1;
78+
}
79+
80+
StringBuilder result = new StringBuilder();
81+
for (StringBuilder sb : rows) {
82+
result.append(sb);
83+
}
84+
85+
return result.toString();
86+
}
87+
88+
public static void main(String[] args) {
89+
Solution solution = new Solution();
90+
91+
// Test cases
92+
String s1 = "PAYPALISHIRING";
93+
int numRows1 = 3;
94+
System.out.println("Example 1 Output: " + solution.convert(s1, numRows1));
95+
96+
String s2 = "PAYPALISHIRING";
97+
int numRows2 = 4;
98+
System.out.println("Example 2 Output: " + solution.convert(s2, numRows2));
99+
100+
String s3 = "A";
101+
int numRows3 = 1;
102+
System.out.println("Example 3 Output: " + solution.convert(s3, numRows3));
103+
}
104+
}
105+
```
106+
107+
This implementation provides a solution to the Zigzag Conversion problem in Java.

0 commit comments

Comments
 (0)