Skip to content

Commit 743379c

Browse files
committed
6. Zigzag Conversion
```Solution.c char* convert(char* s, int numRows) { int sLength = strlen(s); char *res = (char *)malloc((sLength + 1) * sizeof(char)); res[sLength] = '\0'; int resPos = 0; int i = 0; int gap = (numRows - 1) * 2; if(gap == 0) { gap = 1; } for(int j = 0; j < sLength; j+=gap) { res[resPos] = s[j]; resPos++; } int gapLeft = gap; for(i=1; i<numRows-1; i++) { gapLeft-=2; int currGap = gap - gapLeft; for(int j = i; j < sLength; j+= currGap){ res[resPos] = s[j]; resPos++; currGap = gap - currGap; } } for(int j = i; j < sLength && numRows > 1; j+=gap) { res[resPos] = s[j]; resPos++; } return res; } ``` ```Solution.cpp class Solution { public: string convert(string s, int numRows) { if (numRows == 1 || s.length() <= numRows) return s; vector<string> rows(min(numRows, int(s.size()))); int curRow = 0, dir = -1; for (char c : s) { rows[curRow] += c; if (curRow == 0 || curRow == numRows - 1) dir *= -1; curRow += dir; } string ret; for (string row : rows) ret += row; return ret; } }; ``` ```Solution.cs public class Solution { public string Convert(string s, int numRows) { if (numRows == 1 || s.Length <= numRows) return s; var rows = new List<string>(new string[Math.Min(numRows, s.Length)]); int curRow = 0; bool goingDown = false; foreach (char c in s) { rows[curRow] += c; if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown; curRow += goingDown ? 1 : -1; } return string.Join("", rows); } } ``` ```Solution.dart class Solution { String convert(String s, int numRows) { if (numRows == 1 || s.length <= numRows) return s; List<StringBuffer> rows = List.generate(numRows, (_) => StringBuffer()); int curRow = 0; bool goingDown = false; for (var c in s.split('')) { rows[curRow].write(c); if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown; curRow += goingDown ? 1 : -1; } return rows.map((sb) => sb.toString()).join(''); } } ``` ```Solution.erl -spec convert(S :: unicode:unicode_binary(), NumRows :: integer()) -> unicode:unicode_binary(). convert(S, NumRows) when NumRows =< 1; NumRows >= byte_size(S) -> S; convert(S, NumRows) -> Rows = lists:duplicate(NumRows, []), convert(S, NumRows, 1, 1, Rows). convert(<<>>, _NumRows, _CurRow, _Dir, Rows) -> unicode:characters_to_binary(lists:flatten(lists:map(fun lists:reverse/1, Rows))); convert(<<C/utf8, Rest/binary>>, NumRows, CurRow, Dir, Rows) -> NewRows = add_char(Rows, CurRow, C), NewDir = case {CurRow, Dir} of {1, -1} -> 1; {NumRows, 1} -> -1; _ -> Dir end, NewCurRow = CurRow + NewDir, convert(Rest, NumRows, NewCurRow, NewDir, NewRows). add_char(Rows, CurRow, C) -> {NewRows, _} = lists:mapfoldl( fun(Row, Idx) -> if Idx =:= CurRow -> {[C | Row], Idx + 1}; true -> {Row, Idx + 1} end end, 1, Rows), NewRows. ``` ```Solution.ex defmodule Solution do @SPEC convert(s :: String.t, num_rows :: integer) :: String.t def convert(s, 1), do: s def convert(s, num_rows) do cycle_len = 2 * num_rows - 2 0..(num_rows - 1) |> Enum.map(fn row -> add_row(s, num_rows, cycle_len, row) end) |> IO.iodata_to_binary() end def add_row(s, num_rows, cycle_len, row), do: add_row(s, num_rows, cycle_len, row, 0, []) def add_row(s, num_rows, cycle_len, row, cycle, acc) when row + cycle * cycle_len < byte_size(s) do index = row + cycle * cycle_len acc = [:binary.at(s, index) | acc] acc = if row > 0 and row < num_rows - 1 and (cycle + 1) * cycle_len - row < byte_size(s) do index = (cycle + 1) * cycle_len - row [:binary.at(s, index) | acc] else acc end add_row(s, num_rows, cycle_len, row, cycle + 1, acc) end def add_row(_, _, _, _, _, acc), do: Enum.reverse(acc) end ``` ```Solution.go func convert(s string, numRows int) string { if numRows == 1 || len(s) <= numRows { return s } rows := make([]string, min(numRows, len(s))) curRow := 0 goingDown := false for _, c := range s { rows[curRow] += string(c) if curRow == 0 || curRow == numRows-1 { goingDown = !goingDown } if goingDown { curRow++ } else { curRow-- } } return strings.Join(rows, "") } ``` ```Solution.java class Solution { public String convert(String s, int numRows) { if (numRows == 1 || s.length() <= numRows) return s; StringBuilder[] rows = new StringBuilder[Math.min(numRows, s.length())]; for (int i = 0; i < rows.length; i++) rows[i] = new StringBuilder(); int curRow = 0, dir = -1; for (char c : s.toCharArray()) { rows[curRow].append(c); if (curRow == 0 || curRow == numRows - 1) dir *= -1; curRow += dir; } StringBuilder result = new StringBuilder(); for (StringBuilder row : rows) result.append(row); return result.toString(); } } ``` ```Solution.js /** * @param {string} s * @param {number} numRows * @return {string} */ var convert = function(s, numRows) { if (numRows === 1 || s.length <= numRows) return s; let rows = Array(Math.min(numRows, s.length)).fill(''); let curRow = 0, goingDown = false; for (let c of s) { rows[curRow] += c; if (curRow === 0 || curRow === numRows - 1) goingDown = !goingDown; curRow += goingDown ? 1 : -1; } return rows.join(''); }; ``` ```Solution.kt class Solution { fun convert(s: String, numRows: Int): String { if (numRows == 1 || s.length <= numRows) return s val rows = Array(minOf(numRows, s.length)) { StringBuilder() } var curRow = 0 var goingDown = false for (c in s) { rows[curRow].append(c) if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown curRow += if (goingDown) 1 else -1 } return rows.joinToString("") { it.toString() } } } ``` ```Solution.php class Solution { /** * @param String $s * @param Integer $numRows * @return String */ function convert($s, $numRows) { if ($numRows == 1 || strlen($s) <= $numRows) { return $s; } $rows = array_fill(0, $numRows, ""); $curRow = 0; $down = false; for ($i = 0; $i < strlen($s); $i++) { $rows[$curRow] .= $s[$i]; if ($curRow == 0 || $curRow == $numRows - 1) { $down = !$down; } $curRow += $down ? 1 : -1; } return implode("", $rows); } } ``` ```Solution.py class Solution(object): def convert(self, s, numRows): if numRows == 1 or len(s) <= numRows: return s rows = [''] * min(numRows, len(s)) cur_row, going_down = 0, False for c in s: rows[cur_row] += c if cur_row == 0 or cur_row == numRows - 1: going_down = not going_down cur_row += 1 if going_down else -1 return ''.join(rows) ``` ```Solution.rb # @param {String} s # @param {Integer} num_rows # @return {String} def convert(s, num_rows) return s if num_rows == 1 || s.length <= num_rows rows = Array.new([num_rows, s.length].min, "") cur_row, going_down = 0, false s.each_char do |c| rows[cur_row] += c going_down = !going_down if cur_row == 0 || cur_row == num_rows - 1 cur_row += going_down ? 1 : -1 end rows.join end ``` ```Solution.rkt (define (convert s numRows) (if (or (= numRows 1) (<= (string-length s) numRows)) s (let loop ((chars (string->list s)) (rows (make-vector numRows "")) (cur 0) (dir 1)) (if (null? chars) (apply string-append (vector->list rows)) (begin (vector-set! rows cur (string-append (vector-ref rows cur) (string (car chars)))) (let ((new-dir (cond ((= cur 0) 1) ((= cur (- numRows 1)) -1) (else dir)))) (loop (cdr chars) rows (+ cur new-dir) new-dir))))))) ``` ```Solution.rs impl Solution { pub fn convert(s: String, num_rows: i32) -> String { if num_rows == 1 || s.len() <= num_rows as usize { return s; } let mut rows = vec![String::new(); num_rows as usize]; let mut cur_row = 0; let mut down = false; for c in s.chars() { rows[cur_row].push(c); if cur_row == 0 || cur_row == (num_rows - 1) as usize { down = !down; } cur_row = if down { cur_row + 1 } else { cur_row - 1 }; } rows.concat() } } ``` ```Solution.scala object Solution { def convert(s: String, numRows: Int): String = { if (numRows == 1 || s.length <= numRows) return s val rows = Array.fill(Math.min(numRows, s.length))("") var curRow = 0 var goingDown = false for (c <- s) { rows(curRow) += c if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown curRow += (if (goingDown) 1 else -1) } rows.mkString("") } } ``` ```Solution.swift class Solution { func convert(_ s: String, _ numRows: Int) -> String { if numRows == 1 || s.count <= numRows { return s } var rows = Array(repeating: "", count: min(numRows, s.count)) var curRow = 0 var goingDown = false for c in s { rows[curRow] += String(c) if curRow == 0 || curRow == numRows - 1 { goingDown.toggle() } curRow += goingDown ? 1 : -1 } return rows.joined() } } ``` ```Solution.ts function convert(s: string, numRows: number): string { if (numRows === 1 || s.length <= numRows) return s; let rows: string[] = Array(Math.min(numRows, s.length)).fill(""); let curRow = 0; let goingDown = false; for (let c of s) { rows[curRow] += c; if (curRow === 0 || curRow === numRows - 1) goingDown = !goingDown; curRow += goingDown ? 1 : -1; } return rows.join(""); } ```
1 parent 06a6cd2 commit 743379c

19 files changed

+353
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# [**6. Zigzag Conversion**](https://leetcode.com/problems/zigzag-conversion/description/)
2+
3+
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)
4+
5+
```md
6+
P A H N
7+
A P L S I I G
8+
Y I R
9+
```
10+
And then read line by line: `"PAHNAPLSIIGYIR"`
11+
12+
Write the code that will take a string and make this conversion given a number of rows:
13+
> `string convert(string s, int numRows);`
14+
15+
#### **Example 1:**
16+
```md
17+
Input: s = "PAYPALISHIRING", numRows = 3
18+
Output: "PAHNAPLSIIGYIR"
19+
```
20+
21+
#### **Example 2:**
22+
```md
23+
Input: s = "PAYPALISHIRING", numRows = 4
24+
Output: "PINALSIGYAHRPI"
25+
Explanation:
26+
P I N
27+
A L S I G
28+
Y A H R
29+
P I
30+
```
31+
32+
#### **Example 3:**
33+
```md
34+
Input: s = "A", numRows = 1
35+
Output: "A"
36+
```
37+
38+
#### **Constraints:**
39+
> - `1 <= s.length <= 1000`
40+
> - `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
41+
> - `1 <= numRows <= 1000`
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
char* convert(char* s, int numRows) {
2+
int sLength = strlen(s);
3+
char *res = (char *)malloc((sLength + 1) * sizeof(char));
4+
res[sLength] = '\0';
5+
int resPos = 0;
6+
int i = 0;
7+
int gap = (numRows - 1) * 2;
8+
if(gap == 0) {
9+
gap = 1;
10+
}
11+
for(int j = 0; j < sLength; j+=gap) {
12+
res[resPos] = s[j];
13+
resPos++;
14+
}
15+
int gapLeft = gap;
16+
for(i=1; i<numRows-1; i++) {
17+
gapLeft-=2;
18+
int currGap = gap - gapLeft;
19+
for(int j = i; j < sLength; j+= currGap){
20+
res[resPos] = s[j];
21+
resPos++;
22+
currGap = gap - currGap;
23+
}
24+
}
25+
for(int j = i; j < sLength && numRows > 1; j+=gap) {
26+
res[resPos] = s[j];
27+
resPos++;
28+
}
29+
return res;
30+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public:
3+
string convert(string s, int numRows) {
4+
if (numRows == 1 || s.length() <= numRows) return s;
5+
vector<string> rows(min(numRows, int(s.size())));
6+
int curRow = 0, dir = -1;
7+
for (char c : s) {
8+
rows[curRow] += c;
9+
if (curRow == 0 || curRow == numRows - 1) dir *= -1;
10+
curRow += dir;
11+
}
12+
string ret;
13+
for (string row : rows) ret += row;
14+
return ret;
15+
}
16+
};
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
public class Solution {
2+
public string Convert(string s, int numRows) {
3+
if (numRows == 1 || s.Length <= numRows) return s;
4+
var rows = new List<string>(new string[Math.Min(numRows, s.Length)]);
5+
int curRow = 0;
6+
bool goingDown = false;
7+
foreach (char c in s) {
8+
rows[curRow] += c;
9+
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
10+
curRow += goingDown ? 1 : -1;
11+
}
12+
return string.Join("", rows);
13+
}
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
String convert(String s, int numRows) {
3+
if (numRows == 1 || s.length <= numRows) return s;
4+
List<StringBuffer> rows = List.generate(numRows, (_) => StringBuffer());
5+
int curRow = 0;
6+
bool goingDown = false;
7+
for (var c in s.split('')) {
8+
rows[curRow].write(c);
9+
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
10+
curRow += goingDown ? 1 : -1;
11+
}
12+
return rows.map((sb) => sb.toString()).join('');
13+
}
14+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
-spec convert(S :: unicode:unicode_binary(), NumRows :: integer()) -> unicode:unicode_binary().
2+
convert(S, NumRows) when NumRows =< 1; NumRows >= byte_size(S) ->
3+
S;
4+
convert(S, NumRows) ->
5+
Rows = lists:duplicate(NumRows, []),
6+
convert(S, NumRows, 1, 1, Rows).
7+
convert(<<>>, _NumRows, _CurRow, _Dir, Rows) ->
8+
unicode:characters_to_binary(lists:flatten(lists:map(fun lists:reverse/1, Rows)));
9+
convert(<<C/utf8, Rest/binary>>, NumRows, CurRow, Dir, Rows) ->
10+
NewRows = add_char(Rows, CurRow, C),
11+
NewDir = case {CurRow, Dir} of
12+
{1, -1} -> 1;
13+
{NumRows, 1} -> -1;
14+
_ -> Dir
15+
end,
16+
NewCurRow = CurRow + NewDir,
17+
convert(Rest, NumRows, NewCurRow, NewDir, NewRows).
18+
add_char(Rows, CurRow, C) ->
19+
{NewRows, _} = lists:mapfoldl(
20+
fun(Row, Idx) ->
21+
if Idx =:= CurRow -> {[C | Row], Idx + 1};
22+
true -> {Row, Idx + 1}
23+
end
24+
end, 1, Rows),
25+
NewRows.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
defmodule Solution do
2+
@spec convert(s :: String.t, num_rows :: integer) :: String.t
3+
def convert(s, 1), do: s
4+
def convert(s, num_rows) do
5+
cycle_len = 2 * num_rows - 2
6+
0..(num_rows - 1)
7+
|> Enum.map(fn row -> add_row(s, num_rows, cycle_len, row) end)
8+
|> IO.iodata_to_binary()
9+
end
10+
def add_row(s, num_rows, cycle_len, row), do: add_row(s, num_rows, cycle_len, row, 0, [])
11+
def add_row(s, num_rows, cycle_len, row, cycle, acc)
12+
when row + cycle * cycle_len < byte_size(s) do
13+
index = row + cycle * cycle_len
14+
acc = [:binary.at(s, index) | acc]
15+
acc =
16+
if row > 0 and row < num_rows - 1 and (cycle + 1) * cycle_len - row < byte_size(s) do
17+
index = (cycle + 1) * cycle_len - row
18+
[:binary.at(s, index) | acc]
19+
else
20+
acc
21+
end
22+
add_row(s, num_rows, cycle_len, row, cycle + 1, acc)
23+
end
24+
def add_row(_, _, _, _, _, acc), do: Enum.reverse(acc)
25+
end
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
func convert(s string, numRows int) string {
2+
if numRows == 1 || len(s) <= numRows {
3+
return s
4+
}
5+
rows := make([]string, min(numRows, len(s)))
6+
curRow := 0
7+
goingDown := false
8+
for _, c := range s {
9+
rows[curRow] += string(c)
10+
if curRow == 0 || curRow == numRows-1 {
11+
goingDown = !goingDown
12+
}
13+
if goingDown {
14+
curRow++
15+
} else {
16+
curRow--
17+
}
18+
}
19+
return strings.Join(rows, "")
20+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public String convert(String s, int numRows) {
3+
if (numRows == 1 || s.length() <= numRows) return s;
4+
StringBuilder[] rows = new StringBuilder[Math.min(numRows, s.length())];
5+
for (int i = 0; i < rows.length; i++) rows[i] = new StringBuilder();
6+
int curRow = 0, dir = -1;
7+
for (char c : s.toCharArray()) {
8+
rows[curRow].append(c);
9+
if (curRow == 0 || curRow == numRows - 1) dir *= -1;
10+
curRow += dir;
11+
}
12+
StringBuilder result = new StringBuilder();
13+
for (StringBuilder row : rows) result.append(row);
14+
return result.toString();
15+
}
16+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} numRows
4+
* @return {string}
5+
*/
6+
var convert = function(s, numRows) {
7+
if (numRows === 1 || s.length <= numRows) return s;
8+
let rows = Array(Math.min(numRows, s.length)).fill('');
9+
let curRow = 0, goingDown = false;
10+
for (let c of s) {
11+
rows[curRow] += c;
12+
if (curRow === 0 || curRow === numRows - 1) goingDown = !goingDown;
13+
curRow += goingDown ? 1 : -1;
14+
}
15+
return rows.join('');
16+
};

0 commit comments

Comments
 (0)