【JAVA、C++】LeetCode 006 ZigZag Conversion
2024-08-17 22:02:10
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"
解题思路:
观察题目,靠眼力寻找规律即可。如果没有读懂ZigZag的话,请移步
http://blog.csdn.net/zhouworld16/article/details/14121477
java实现:
static public String convert(String s, int nRows) {
if (s == null || s.length() <= nRows || nRows <= 1)
return s; StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i += (nRows - 1) * 2)
sb.append(s.charAt(i)); for (int i = 1; i < nRows - 1; i++) {
for (int j = i; j < s.length(); j += (nRows - 1) * 2) {
sb.append(s.charAt(j));
if (j + (nRows - i - 1) * 2 < s.length()) {
sb.append(s.charAt(j + (nRows - i - 1) * 2));
}
}
} for (int i = nRows - 1; i < s.length(); i += (nRows - 1) * 2)
sb.append(s.charAt(i)); return new String(sb);
}
C++实现如下:
#include<string>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
if (s.length() <= numRows || numRows <= )
return s; string sb;
for (int i = ; i < s.length(); i += (numRows - ) * )
sb+=s[i];
for (int i = ; i < numRows - ; i++) {
for (int j = i; j < s.length(); j += (numRows - ) * ) {
sb+=s[j];
if (j + (numRows - i - ) * < s.length())
sb+=s[j + (numRows - i - ) * ];
}
} for (int i = numRows - ; i < s.length(); i += (numRows - ) * )
sb += s[i];
return sb;
}
};
最新文章
- Android Fragment使用(三) Activity, Fragment, WebView的状态保存和恢复
- SQL Server跨库复制表数据错误的解决办法
- 研究validation插件到现在的感受
- BZOJ 2763
- Testlink接口使用方法-python语言远程调用
- mvc中HttpPost理解
- Redis中各种方法的使用
- Spring AOP中的JDK和CGLib动态代理哪个效率更高?
- gooflow学习笔记
- python locust 性能测试:locust 关联---提取返回数据并使用
- stylus解决移动端1像素边框的问题
- PHP const关键字
- mac系统下安装mysql 和phpmyadmin
- WinRAR的自解压模式 - imsoft.cnblogs
- Chrome英文版离线安装包下载
- Qt::浅谈信号槽连接,参数在多线程中的使用
- 洛谷P3939 数颜色(二分 vector)
- PAT L1-034 点赞
- 迁移数据到历史表SQL(转)
- Java基础之this关键字的作用