ZigZag Conversion - LeetCode 6
来源:互联网 发布:韩顺平java视频有用吗 编辑:程序博客网 时间:2024/05/16 04:14
题目描述:
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 LS 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".
Hide Tags String
分析:所谓ZigZag Conversion,就是将一个字符串根据指定行数,按照“蛇形”的排列起来,此处的“蛇形”是先竖直方向,然后副对角线方向,从左往右进行。举个栗子:
将序列"0123456789876543210"按5行进行转换后为:
0 8 2
1 79 31
2 6 8 4 0
35 75
4 6
那么得到的输出序列则为:"0821793126840357546"
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 LS 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".
Hide Tags String
分析:所谓ZigZag Conversion,就是将一个字符串根据指定行数,按照“蛇形”的排列起来,此处的“蛇形”是先竖直方向,然后副对角线方向,从左往右进行。举个栗子:
将序列"0123456789876543210"按5行进行转换后为:
0 8 2
1 79 31
2 6 8 4 0
35 75
4 6
那么得到的输出序列则为:"0821793126840357546"
于是可以将转换后的元素按行存起来,然后再拼接起来即可。
以下是C++实现代码:
/*///////////24ms/*/class Solution {public: string convert(string s, int n) { if(n == 1)return s; vector<string> vec(n,""); //存储转换后的每行int len = s.size();int i = 0,j = 0;while(i < len){for(j = 0;j < n && i < len; j++)vec[j].push_back(s[i++]); // 竖直方向,上到下,需要n个字符,依次字符追加到对应行的字符串中for(j = j-2;j > 0 && i < len; j--)vec[j].push_back( s[i++]); //副对角线方向,下到上,一共需要n-2个字符,依次字符追加到对应行的字符串中}string res = "";for(int j = 0; j < n; j++) // 拼接得到结果字符串res.append(vec[j]);return res; }};
0 0
- LeetCode 6 - ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- LeetCode(6)ZigZag Conversion
- Leetcode【6】:ZigZag Conversion
- [leetcode 6] ZigZag Conversion
- LeetCode 6 ZigZag Conversion
- LeetCode(6) ZigZag Conversion
- [Leetcode] 6 - ZigZag Conversion
- LeetCode 6:《ZigZag Conversion》
- [leetcode 6] ZigZag Conversion
- LeetCode | #6 ZigZag Conversion
- [leetcode] 6 ZigZag Conversion
- leetCode #6 ZigZag Conversion
- leetcode 6 ZigZag Conversion
- leetcode-6 ZigZag Conversion
- leetcode 6 ZigZag Conversion
- LeetCode 6 - ZigZag Conversion
- leetcode 6ZigZag Conversion
- Java Servlet学习笔记(四)Servlet客户端Http请求
- Java基础知识之IO(1)
- Machine Learning多变量梯度下降
- 互联网女皇”Mary Meeker 2015互联网趋势报告说了些什么
- 2 Sum-LintCode
- ZigZag Conversion - LeetCode 6
- View.inflate(Context,layout,null)中null的含义
- mysql基本语法
- 我是如何从勉强写冒泡成长到轻松get百度offer? (内有许多优质算法书籍介绍及推荐)
- 不使用virtual关键字 模拟虚函数来表现多态性
- java|android 使用socket.io-client连接nodejs websocket
- 错误 CUICatalog: Invalid asset name supplied: (null), or invalid scale factor: 2.000000
- android开发工具-SDK国内下载网址
- C++ this指针的用法