未验证 提交 1809fa55 编写于 作者: K Keqi Huang 提交者: GitHub

Merge pull request #262 from ruanwenjun/leetcode-java

Add Java solution 6,7
# 5. ZigZag Conversion
**<font color=red>难度: Medium</font>**
## 刷题内容
> 原题连接
* https://leetcode-cn.com/problems/zigzag-conversion/description
> 内容描述
```
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
```
## 解题方案
> 思路 1
******- 时间复杂度: O(len(s))******- 空间复杂度: O(len(s))******
需要将字符串s转换为按N排列,总共有numRows行,直接将字符串转换为N字形,然后输出, beats 74.18%
```java
class Solution {
// 将字符串进行z子排列,行数为numRows
public String convert(String s, int numRows) {
// 思路:先转换为z字
List[] arr = new List[numRows]; // 保存每一行元素
for(int i = 0; i < numRows; i ++){
arr[i] = new ArrayList();
}
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length;){
// 每次打印两列
for(int j = 0; j < numRows && i < chars.length; j++,i++){
List list = arr[j];
list.add(chars[i]);
}
for(int j = numRows - 1; j >= 0 && i < chars.length; j --){
if(j == numRows - 1 || j == 0){
arr[j].add(' ');
}else{
arr[j].add(chars[i]);
i++;
}
}
}
// 输出最终字符串
char[] result = new char[chars.length];
int index = 0;
for(int i = 0; i < numRows; i ++){
List list = arr[i];
for(int j = 0; j < list.size(); j ++){
if(' ' != (char)list.get(j)){
result[index++] = (char) list.get(j);
}
}
}
return new String(result);
}
}
```
# 5. Reverse Integer
**<font color=red>难度: Easy</font>**
## 刷题内容
> 原题连接
* https://leetcode-cn.com/problems/reverse-integer/description
> 内容描述
```
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
```
## 解题方案
> 思路 1
******- 时间复杂度: O(n)******- 空间复杂度: O(1)******
将整数翻转,翻转后是否溢出了, beats 95.35%
```java
class Solution {
public int reverse(int x) {
// 使用一个long型变量来保存
long index = 0;
while (x != 0){
index = index * 10 + x %10;
x = x / 10;
}
int result = (int) index;
if(result != index){
return 0;
}
return (int)index;
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册