Leetcode_ZigZag Conversion(c++ version)
来源:互联网 发布:cmd查找mac 编辑:程序博客网 时间:2024/05/22 02:30
地址:http://oj.leetcode.com/problems/zigzag-conversion/
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"
.思路:模拟题。另外一直没有判断nRows <= 1 而一直报MLE。
参考代码:
class Solution {public: string convert(string s, int nRows) { if(nRows <=1) { return s; } string str; for(int i = 0; i < nRows; ++i) { for(int j = 0; i+j*(2*nRows-2)<s.length(); ++j) { str+=s[i+j*(2*nRows-2)]; if(i > 0 && i < nRows-1) { if(i+(j+1)*(2*nRows-2)-2*i<s.length()) { str+=s[i+(j+1)*(2*nRows-2)-2*i]; } } } } return str; }};
second trial
注意len<=nRows的特殊情况,算出相对位置。可以把第一行和最后一行做特殊处理。
class Solution {public: string convert(string s, int nRows) { string ans; int len = s.length(); if(len<=nRows || nRows==1) return s; int j; for(int i = 0; i<nRows; ++i) { j = i; while(j<len) { ans += s[j]; if(!i || i==nRows-1) j += 2*(nRows-1); else { j += 2*(nRows-1)-2*i; if(j<len) ans += s[j]; j += 2*i; } } } return ans; }};
0 0
- Leetcode_ZigZag Conversion(c++ version)
- Leetcode_ZigZag Conversion
- LeetCode_ZigZag Conversion
- LeetCode_ZigZag Conversion
- leetcode_zigzag conversion
- LeetCode_ZigZag Conversion_006
- leetcode_zigzag转化
- C++/COM string conversion
- 【leetcode c++】ZigZag Conversion
- 006ZigZag Conversion (C)
- [LeetCode]ZigZag Conversion(C++)
- [C++]LeetCode: 11 ZigZag Conversion
- LeetCode::Zigzag Conversion C语言
- [C++]ZigZag Conversion 之字形转换
- ZigZag Conversion (C实现)
- [C++] LeetCode #6 ZigZag Conversion
- Leetcode c语言-ZigZag Conversion
- Hex to String Conversion C++/C/Qt?
- [OOP]hw002 Student2
- 一篇文章就能掌握SPI总线
- 《Head First 设计模式》命令模式
- IOS高级开发~Runtime(四)
- Java中的equals()和hashCode()契约
- Leetcode_ZigZag Conversion(c++ version)
- servlet简单使用filter解决编码问题
- Validate Binary Search Tree
- delphi cmd
- ASIHTTPRequest详细介绍,使用方法
- Unity3D如何有效地组织代码?
- 第八章--内存管理
- Java中,break和continue的使用区别
- Linux 学习站点收集