LeetCode 6. ZigZag Conversion 解题报告
2016-09-01 00:27
375 查看
题目描述:
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 text, int nRows);
convert("PAYPALISHIRING", 3)should
return
"PAHNAPLSIIGYIR".
解题思路:
本题题意为以z字形格式排列的字符串逐行读出来。由于行数不确定,所以使用vector相对于数组来说更方便一些。使用一个bool变量odd来标记此时字符向下排列(如)还是斜向上方排列。
P 4000 A H N A P L S I I G Y I R p->A->Y即为odd为真时向下排列
向下排列
P A H N A P L S I I G Y 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;
}
};
相关文章推荐
- 夺命雷公狗---node.js---16之项目的构建在node+express+mongo的博客项目1
- Activity学习笔记
- 如何做一名主程之Unity3D网络游戏服务器架构设计
- 图论练习册
- java 利用集合实现斗地主算法
- [4] rw_《CSAPP》2Ed 8 11-12 章 《APUE》15章·简
- Gym 100960G Youngling Tournament(splay)
- smartqq的开源机器人实现管理系统信息推送qq群
- java.util.Vector
- 关于调用相册访问时选择未授权的一个BUG
- linux实施流量监测工具 mark
- 由swr_get_delay想到的
- sublime text3环境下的python即时编译插件
- 基础系列(一):命令
- Java垃圾回收机制
- Android之QQ登录界面
- SqlServer windowss身份登陆和sa身份登陆
- LintCode:最近公共祖先
- python之路 - 爬虫
- Leetcode 234. Palindrome Linked List