forked from lexrus/LeetCode.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6.swift
113 lines (90 loc) · 2.87 KB
/
6.swift
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//
// ZigZagConversion.swift
// ZigZagConversion
//
// Created by Lex Tang on 4/16/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
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)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
*/
import Foundation
import XCTest
class ZigZagConversion {
/**
This Swift method is imitated from the C++ method found here:
https://github.com/haoel/leetcode/blob/master/algorithms/zigZagConversion/zigZagConversion.cpp
- parameter text: Source text
- parameter rows: Number of rows
- returns: The result ZigZag text
*/
class func convert0(text: String, _ rows: Int) -> String {
if rows <= 1 || rows > text.characters.count {
return text
}
var r = [String]()
var row = 0
var step = 1
for (_, char) in text.characters.enumerate() {
if row == rows - 1 {
step = -1
}
if row == 0 {
step = 1
}
if row > r.count - 1 {
r.append("\(char)")
} else {
r[row].append(char)
}
row += step
}
var result = ""
var i = 0
while i < rows {
result.appendContentsOf(r[i])
i++
}
return result
}
}
extension ZigZagConversion {
/**
O (N)
This solution is copied from here:
https://github.com/diwu/LeetCode-Solutions-in-Swift/blob/master/Solutions/Solutions/Easy/Easy_006_ZigZag_Conversion.swift
- parameter text: Source text
- parameter rows: Number of rows
- returns: The result ZigZag text
*/
class func convert1(text: String, _ rows: Int) -> String {
var array = Array<String>(count: rows, repeatedValue: String())
var i = 0, length = text.characters.count
while i < length {
for var index = 0; index < rows && i < length; index++ {
array[index].append(text[i++]!)
}
for var index = rows - 2; index > 0 && i < length; index-- {
array[index].append(text[i++]!)
}
}
var result = ""
for i in 0 ..< rows {
result.appendContentsOf(array[i])
}
return result
}
}
class ZigZagConversionTest: XCTestCase {
func testZigZagConvert() {
XCTAssertEqual(ZigZagConversion.convert0("PAYPALISHIRING", 3), "PAHNAPLSIIGYIR", "")
XCTAssertEqual(ZigZagConversion.convert1("PAYPALISHIRING", 3), "PAHNAPLSIIGYIR", "")
}
}