[leetcode]ZigZag Conversion
来源:互联网 发布:科颜氏洗发水知乎 编辑:程序博客网 时间:2024/06/07 17:13
ZigZag Conversion
Difficult:Medium
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 NA P L S I I GY I RAnd 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"
.
分析:
问题就是要Z字型输出字符串。
我的实现方法是按要求的行数创建临时的字符串(例如当行数等于3时有s1、s2、s3三个字符串),遍历输入的字符串的时候,按Z字型的顺序把每一位字符放接到临时字符串后边(比如第1个字符接s1后面,第2个接s2,第3个接s3,第4个就又接到s2,第5个接s1,第6个接s2.....),最后再把临时字符串接在一起就好了
string convert(string s, int numRows) { vector<string> v_result; for (int i = 0; i < numRows; i++){ v_result.push_back("");//按行数生成临时字符串 } int step = 1;//初始步进1,步进为1或-1 if (numRows < 2)//如果行数为1则步进为0 step = 0; int current = 0; for (int i = 0; i < s.size(); i++){ stringstream stream; stream << s.at(i); string tmp = stream.str(); v_result.at(current).append(tmp);//接到相应的临时字符串后面 current = current + step;//加上步进 if (current == 0 || current == numRows - 1)//当current为0或行数时,反转步进 step = step*-1; } string result = ""; for (int i = 0; i < numRows; i++){ result.append(v_result.at(i)); } return result; }
0 0
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- Leetcode : ZigZag Conversion
- 【leetcode】Zigzag Conversion
- [LeetCode]ZigZag Conversion
- leetcode ZigZag Conversion
- LeetCode-ZigZag Conversion
- LeetCode ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- leetcode-006:ZigZag Conversion
- Leetcode: ZigZag Conversion
- [LeetCode]ZigZag Conversion
- [LeetCode] ZigZag Conversion
- [LeetCode]ZigZag Conversion
- leetcode: ZigZag Conversion
- Nebula_Level00
- 使用spring的JdbcTemplate进行查询的三种回调方式的比较
- [jvm][面试] 并发收集器 CMS(Concurrent Mark-Sweep)
- python之TCP客户端和服务器端编写
- Codeforces Round #306 (Div. 2) B. Preparing Olympiad dfs
- [leetcode]ZigZag Conversion
- 归并排序,插入排序,快速排序,冒泡排序,选择排序的思想
- [数据库]存储过程
- Eclipse下的java工程目录问题和Classpath路径问题理解
- 集合3
- PHP配置Memcached
- 设计模式学习--单例模式
- mac终端一直显示进程已完成
- 试试看