-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathZigZagConversation.java
More file actions
37 lines (31 loc) · 1.09 KB
/
ZigZagConversation.java
File metadata and controls
37 lines (31 loc) · 1.09 KB
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
package swe.Strings;
import java.util.Arrays;
public class ZigZagConversation {
public static String zigzagConstruct(String str, int rows) {
if (rows == 1) {
return str;
}
String[] zigzag = new String[rows];
Arrays.fill(zigzag, "");// zigzag = {"", "", ""}
int currentRow = 0;
boolean goingDown = false;
for (char c : str.toCharArray()) {
zigzag[currentRow] += c;
if (currentRow == 0 || currentRow == rows - 1) {
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}
StringBuilder sb = new StringBuilder();
for (String row:
zigzag) {
sb.append(row);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(zigzagConstruct("YELLOWPINK", 4)); // YPEWILONLK
System.out.println(zigzagConstruct("REDBLUEBLACK", 2)); // RDLELCEBUBAK
System.out.println(zigzagConstruct("REDBLUEBLACK", 1)); // REDBLUEBLACK
}
}