标签:tps str tco write size ash btn category interval
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 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"
. 首先第一行和最后一个行的间隔是2*n-2个元素
注意i是从0开始的,从1开始就减去1.
#include <bits/stdc++.h> #define INF 0x3fffffff #define eps 1e-8 typedef long long LL; const double pi = acos(-1.0); const int mod = 1e9 + 7; const int maxn = 70; using namespace std; string convert(string s, int nRows) { if(nRows == 1)return s; int len = s.size(), k = 0, interval = (nRows<<1)-2; string res(len, ‘ ‘); for(int j = 0; j < len ; j += interval)//处理第一行 res[k++] = s[j]; for(int i = 1; i < nRows-1; i++)//处理中间行 { int inter = (i<<1);//就是i*2,写成位运算是不是高大上一些 for(int j = i; j < len; j += inter) { //第一次加的就是字符串第一列的 res[k++] = s[j]; inter = interval - inter;//interval–2*i或者interval-(interval–2*i)=2*i } } for(int j = nRows-1; j < len ; j += interval)//处理最后一行 res[k++] = s[j]; return res; } int main() { freopen("in.txt","r",stdin); string ss; cin>>ss; cout<<convert(ss, 5); return 0; }
标签:tps str tco write size ash btn category interval
原文地址:http://www.cnblogs.com/zhangmingzhao/p/7347300.html