File tree Expand file tree Collapse file tree 1 file changed +9
-3
lines changed Expand file tree Collapse file tree 1 file changed +9
-3
lines changed Original file line number Diff line number Diff line change 40
40
public class MyClass {
41
41
public static String convert (String s , int numRows ) {
42
42
int flag = -1 ;
43
+
43
44
HashMap < Integer , String > map = new HashMap < > ();
44
45
int pos = 0 ;
45
46
String word = "" ;
46
47
if (numRows <= 1 )
47
48
return s ;
48
49
else {
50
+ // traversing in zig zag pattern and storing the data of each row in hashtable as string
49
51
for (int x = 0 ; x < s .length (); x ++) {
50
52
char ch1 = s .charAt (x );
51
53
String ch = Character .toString (ch1 );
@@ -54,27 +56,31 @@ public static String convert(String s, int numRows) {
54
56
flag = 1 ;
55
57
if (map .containsKey (pos )) {
56
58
String a = map .get (pos );
59
+ // concatinating the previous word along with new character
57
60
String w = a + ch ;
58
61
map .put (pos , w );
59
62
} else {
60
63
map .put (pos , ch );
61
64
}
65
+ // once reached the end of the row start moving upwards i.e decreasing the key in hash table
62
66
pos --;
63
-
64
- } else if (pos == 0 || flag == 0 ) {
67
+ }
68
+ else if (pos == 0 || flag == 0 ) {
65
69
flag = 0 ;
70
+ // check if the key in hash table has some data present
66
71
if (map .containsKey (pos )) {
67
72
String a = map .get (pos );
68
73
String w = a + ch ;
69
-
70
74
map .put (pos , w );
71
75
} else {
72
76
map .put (pos , ch );
73
77
}
78
+ // keep increasing the key i.e pos in hash table till we reach at the end of the row
74
79
pos ++;
75
80
}
76
81
}
77
82
for (Map .Entry < Integer , String > e : map .entrySet ())
83
+ // concatinate the values of each row of hash table
78
84
word = word + e .getValue ();
79
85
80
86
return word ;
You can’t perform that action at this time.
0 commit comments