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"
.
用簡單的模擬來做,下面附上我的代碼:
<pre name="code" class="cpp">class Solution {
public:
char **arr;
string convert(string s, int numRows) {
if (numRows==1||s.length()==0) {
return s;
}
//計算行數列數
int Y;
if ((numRows*2-2)!=0) {
Y=(int)((numRows*s.length())/(numRows*2-2))+1;
}else{
Y=1;
}
int X=numRows;
arr= new char *[X];
for (int i=0; i<X; i++) {
arr[i]=new char[Y];
}
//初始化數組
for (int i=0; i<X; i++) {
for (int j=0; j<Y; j++) {
arr[i][j]=0;
}
}
string ans;
int vertical=1;
int i=0;
int j=0;//數組下標
for (int k =0; k<s.length(); k++) {
arr[i][j]=s[k];
//逐個字符遍歷
if (vertical&&i!=numRows-1) {//如果是豎直的並且還沒到num個
i++;//下一次擺放的位置
continue;
}
if (vertical&&i==numRows-1) {//如果是豎着的已經num個了
vertical=0;
i--;
j++;//下一次擺放的位置
continue;
}
if (!vertical&&i!=0) {//如果是對角線,沒到頂。
i--;j++;//下一次擺放的位置。
continue;
}
if (!vertical&&i==0) {//如果是對角線,到頂了。
i++;//下一次開始一個新的豎着的
vertical=1;
}
}
ans=toString(s.length(),X, Y);
return ans;
}
string toString(int size,int X,int Y){
char temparr[1000];
int count=0;
memset(temparr, 0, sizeof(temparr));
for (int i=0; i<X; i++) {
for (int j=0; j<Y; j++) {
char c=arr[i][j];
if (c!=0) {
temparr[count++]=c;
size--;
if (size==0) {
break;
}
}
}
}
return (string)temparr;
}
};
同學的代碼:
其思路是每個循環賦值好一個豎排加上一個對角線:
string convert(string s, int numRows){
if(numRows == 1)
return s;
long len = s.size();
long n = (len/(2*numRows-2) +1)*numRows;
char **array;
array = new char*[numRows];
for(int i = 0; i < numRows; i++){
array[i] = new char[n];
}
for(int i = 0; i < numRows; i++)
for(int j = 0; j < n; j++)
array[i][j] = ' ';
int cur = 0, i = 0, j = 0;
while(cur < s.size()){
for(; i < numRows && cur < s.size(); i++, cur++)
array[i][j] = s[cur];
i -= 2;
j++;
for(; i >= 0 && cur < s.size(); i--, j++, cur++)
array[i][j] = s[cur];
i += 2;
}
string s1;
for(i = 0; i < numRows; i++)
for(j = 0; j < n; j++)
if(array[i][j] != ' ')
s1 += array[i][j];
return s1;
}