Skip to content

Commit ca17534

Browse files
committed
code added
1 parent 1d832a5 commit ca17534

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// PROBLEM STATEMENT ALONG WITH TEST CASE
2+
// The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
3+
4+
// P A H N
5+
// A P L S I I G
6+
// Y I R
7+
// And then read line by line: "PAHNAPLSIIGYIR"
8+
9+
// Write the code that will take a string and make this conversion given a number of rows:
10+
11+
// string convert(string s, int numRows);
12+
13+
14+
// Example 1:
15+
16+
// Input: s = "PAYPALISHIRING", numRows = 3
17+
// Output: "PAHNAPLSIIGYIR"
18+
// Example 2:
19+
20+
// Input: s = "PAYPALISHIRING", numRows = 4
21+
// Output: "PINALSIGYAHRPI"
22+
// Explanation:
23+
// P I N
24+
// A L S I G
25+
// Y A H R
26+
// P I
27+
// Example 3:
28+
29+
// Input: s = "A", numRows = 1
30+
// Output: "A"
31+
32+
33+
// Constraints:
34+
35+
// 1 <= s.length <= 1000
36+
// s consists of English letters (lower-case and upper-case), ',' and '.'.
37+
// 1 <= numRows <= 1000
38+
39+
import java.util.*;
40+
public class MyClass {
41+
public static String convert(String s, int numRows) {
42+
int flag = -1;
43+
HashMap < Integer, String > map = new HashMap < > ();
44+
int pos = 0;
45+
String word = "";
46+
if (numRows <= 1)
47+
return s;
48+
else {
49+
for (int x = 0; x < s.length(); x++) {
50+
char ch1 = s.charAt(x);
51+
String ch = Character.toString(ch1);
52+
53+
if (pos == (numRows - 1) || flag == 1 && pos > 0) {
54+
flag = 1;
55+
if (map.containsKey(pos)) {
56+
String a = map.get(pos);
57+
String w = a + ch;
58+
map.put(pos, w);
59+
} else {
60+
map.put(pos, ch);
61+
}
62+
pos--;
63+
64+
} else if (pos == 0 || flag == 0) {
65+
flag = 0;
66+
if (map.containsKey(pos)) {
67+
String a = map.get(pos);
68+
String w = a + ch;
69+
70+
map.put(pos, w);
71+
} else {
72+
map.put(pos, ch);
73+
}
74+
pos++;
75+
}
76+
}
77+
for (Map.Entry < Integer, String > e: map.entrySet())
78+
word = word + e.getValue();
79+
80+
return word;
81+
}
82+
}
83+
//main function
84+
public static void main(String args[]) {
85+
Scanner sc = new Scanner(System.in);
86+
String s = sc.next();
87+
int rows = sc.nextInt();
88+
System.out.println(convert(s, rows));
89+
90+
}
91+
}

0 commit comments

Comments
 (0)