LeetCode 6. ZigZag Conversion 解题报告
来源:互联网 发布:php.ini设置文件大小 编辑:程序博客网 时间:2024/06/06 09:05
题目描述:
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字形格式排列的字符串逐行读出来。由于行数不确定,所以使用vector相对于数组来说更方便一些。使用一个bool变量odd来标记此时字符向下排列(如)还是斜向上方排列。
P A H NA P L S I I GY I R p->A->Y即为odd为真时向下排列
向下排列
P A H NA P L S I I GY I R Y->P->A为斜向上排列。但是此时Y和A分别被包含在前两个向下的排列中。P则在odd为假时被加入第二行。
斜向上排列
代码展示:
#include <iostream>#include <string>#include <vector>class Solution {public: string convert(string s, int numRows) { vector<char> tmp; vector<vector<char> > res; for(int i=0 ; i<numRows ; i++) { res.push_back(tmp); } bool flag =false; //int jj =0; bool odd = true;//odd 标记序列向下移动 for(int i=0 ; i<s.size()&&!flag;) { if(odd) { for(int j=0; j<numRows ;j++) { res[j].push_back(s[i]); i++; if(i==s.size()) { flag = true; break; } } odd = !odd; } else { for(int j=numRows-2; j>0 ;j--) { res[j].push_back(s[i]); i++; if(i==s.size()) { flag = true; break; } } odd = !odd; } } string ans; for(int i=0;i<res.size();i++) { for(int j=0 ; j<res[i].size();j++) ans+=res[i][j]; } return ans;}};
0 0
- [leetcode] 6. ZigZag Conversion 解题报告
- LeetCode 6. ZigZag Conversion 解题报告
- [Leetcode] 6. ZigZag Conversion 解题报告
- leetcode解题报告6. ZigZag Conversion
- 【LeetCode】6.ZigZag Conversion(Medium)解题报告
- 【LeetCode】ZigZag Conversion 解题报告
- LeetCode ZigZag Conversion 解题报告
- LeetCode解题报告--ZigZag Conversion
- [LeetCode] ZigZag Conversion 解题报告
- [LeetCode] ZigZag Conversion 解题报告
- Leetcode ZigZag Conversion解题报告
- LeetCode解题报告 6. ZigZag Conversion[easy]
- [LeetCode 解题报告]006.ZigZag Conversion
- LeetCode(6) ZigZag Conversion解题报告
- 【Leetcode】6.ZigZag Conversion 解题
- ZigZag Conversion解题报告
- LeetCodeProblem6 ZigZag Conversion解题报告
- [Leetcode]解题文档-ZigZag Conversion
- 图论练习册
- [4] rw_《CSAPP》2Ed 8 11-12 章 《APUE》15章·简
- java 利用集合实现斗地主算法
- 如何做一名主程之Unity3D网络游戏服务器架构设计
- Activity学习笔记
- LeetCode 6. ZigZag Conversion 解题报告
- jdk1.7实现ftp上传文件
- WEB——Cookie案例
- RxJava操作符(一)Creating Observables
- RxJava操作符(二)Transforming Observables
- lnmp环境搭建
- RxJava操作符(三)Filtering
- 我心永恒
- Nginx动静分离