Leetcode 6. ZigZag Conversion
2016-04-21 21:59
429 查看
The string
this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
return
核心思想:找出循环单元 如上面的例子 当nRows是时,原串的每个字符对应的行数为 1 2 3 2 1 2 3 2 1 2 3 2 1 2 ,很容易看出循环结构为 1 2 3 2 长度为:2*3-2
代码如下:
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1||s=="")
return s;
string ss[numRows];//用来存储相应行号的串
int flag;//用来存储原串字母对应行号
for(int i=0;i<s.size();i++){
flag=(i+1)%(2*numRows-2);
if(flag>numRows)
flag=2*numRows-flag;
if(flag==0)
flag=2;
ss[flag-1]+=s[i];
}
string ans;
for(int i=0;i<numRows;i++)
ans+=ss[i];
return ans;
}
};
"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".
核心思想:找出循环单元 如上面的例子 当nRows是时,原串的每个字符对应的行数为 1 2 3 2 1 2 3 2 1 2 3 2 1 2 ,很容易看出循环结构为 1 2 3 2 长度为:2*3-2
代码如下:
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1||s=="")
return s;
string ss[numRows];//用来存储相应行号的串
int flag;//用来存储原串字母对应行号
for(int i=0;i<s.size();i++){
flag=(i+1)%(2*numRows-2);
if(flag>numRows)
flag=2*numRows-flag;
if(flag==0)
flag=2;
ss[flag-1]+=s[i];
}
string ans;
for(int i=0;i<numRows;i++)
ans+=ss[i];
return ans;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- 关于指针的一些事情
- android上改变listView的选中颜色
- String.intern
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Prototype源码浅析 String部分(二)
- Ruby中的String对象学习笔记
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- PostgreSQL ERROR: invalid escape string 解决办法
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析