//思路就是找出zigzag序列每一横行
//(一共numRows横行)
//中各个字符在原字符串s中下标的间隔是多少
//依次输出即可
class Solution {
public:
string convert(string s, int numRows) {
if((s.size()<=numRows)||(numRows==1)) return s;
int gap = 2*(numRows - 1);
int each_gap;
bool is_finish = 0;
string str;
for(int i=0;i<numRows;i++){
int j = i;
//cout<<"i:"<<i<<endl;
if((i!=(numRows-1))&&(i!=0)){
each_gap = gap - 2*i;
for(;;){
str.push_back(s[j]);
//cout<<"s["<<j<<"]:"<<s[j]<<endl;
j = j + each_gap;
each_gap = gap-each_gap;
if(j>s.size()-1){
each_gap = gap-2*(i+1);
break;
}
}
}
else{//头尾处
each_gap = gap;
for(;;){
str.push_back(s[j]);
//cout<<"s["<<j<<"]:"<<s[j]<<endl;
j = j + each_gap;
if(j>(s.size()-1)){
if(i!=0){is_finish = 1;}
break;
}
}
}
if(is_finish) break;
}
return str;
}
};
LeetCode_#6_ZigZag_Conversion
最新推荐文章于 2018-10-26 11:58:00 发布