leetcode6 ZigZag Conversion
来源:互联网 发布:西安中国银行软件中心 编辑:程序博客网 时间:2024/05/29 14:14
这个leetcode上的题目写的就是太简单了,就是简单一句话加上一个测试用例就完事了,不严谨,总是理解错,这个让我很闹心啊.
大概题意就是,将字符串排列成连续的折线,就像是很多个N连在一起那种,之后再按行相加然后返回就OK了.
仔细观察图形可以发现,第一行和最后一行是可直接循环相加的,不需要加中间的那些字符,字符串的循环周期为
crcle = (numRows-1)*2;
比如说举一个numRows为6的例子,crcle就是10,第一行和最后一行直接以10为周期循环相加就OK了,但是中间的四行就必须得每次循环加两个字符,一个是循环周期中的字符,另外一个是中间斜线上的字符,他们中间有对应的规律就是1-9,2-8,
3-7,4-6,其实就是crcle-i,每次循环的时候都要加crcle那么就是k*crcle+crcle-1(k=0,1,2,3,4......).我们只需将表达式变成这样就OK了.
代码:
#include<stdio.h>#include<iostream>#include<string.h>#include<algorithm>using namespace std;class Solution {public: string convert(string s, int numRows) { int i,j,len; int crcle; string strtemp = ""; len = s.capacity(); crcle = numRows+1; if(numRows == 1 || numRows >= len) { return s; } crcle = (numRows-1)*2; for(i=0;i<numRows;i++) { for(j=i;j<len;j+=crcle) { strtemp+=s[j]; if(i==0||i==numRows-1) continue; else if((j+crcle-(2*i))<len) strtemp+=s[j+crcle-(2*i)]; } } return strtemp; }};int main(){string result = "PAHNAPLSIIGYIR";string s= "PAYPALISHIRING";int num = 3;Solution test;cout<<result<<endl;result = test.convert(s,num);cout<<result<<endl;return 0;}
0 0
- LeetCode6:ZigZag Conversion
- leetcode6-ZigZag Conversion
- leetcode6 Zigzag Conversion
- [Java]leetcode6 ZigZag Conversion
- ZigZag Conversion leetcode6
- leetcode6 ZigZag Conversion
- LeetCode6:ZigZag Conversion
- LeetCode6. ZigZag Conversion
- leetcode6. ZigZag Conversion
- Leetcode6: ZigZag Conversion
- leetcode6. ZigZag Conversion
- leetcode6. ZigZag Conversion
- Leetcode6、ZigZag Conversion
- LeetCode6. ZigZag Conversion
- ZigZag Conversion(leetcode6)
- LeetCode6—ZigZag Conversion
- leetcode6. ZigZag Conversion
- LeetCode6——ZigZag Conversion
- 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
- POJ 1844:Sum ”滚动“数组
- 浅谈面向对象第二枪
- Cookie:记录用户最近商品的访问记录
- 1038. 统计同成绩学生(20)
- leetcode6 ZigZag Conversion
- 奇怪的连接错误 LNK1181: 无法打开输入文件“,5.01”
- HDU 5427
- 字符串左移
- 分享一个仿Eclipse配色的Android Studio主题配置文件
- LA 3126 - Taxi Cab Scheme【DAG最小路径覆盖】
- ios-自定义画板
- SGU101 Domino(欧拉回路)
- 牛客面试常考算法题精讲部分题目c/c++代码