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 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"
.
一開始根本不懂她的規律到底是怎樣
查了一下原來是
nRows = 3 0 4 8 ... 1 3 5 7 9 2 6 10
nRows = 4 0 6 12 ... 1 5 7 11 2 4 8 10 3 9
每一個row的跳躍剛好是 2*(nRows - 1)
所以算好就好了
原本一開始用char ans [size]
但是超過一次的測資會爆炸
(最下面更新了!!)
remin 是在row!=0 and row!=numRows-1 的狀態下多出來了
numRows=4的情況下
row1 會是 1 5 7 11
1->5:4
5->7:2
兩個加起來一定會是6
所以每次都會選擇要加哪個數字
後來想想好像多此一舉
可以改成
ans[count]= s[index];
index=index+jump;
if( row!=0 || row!=numRows-1 ){
ans[++count]= s[index]+2*(numRows-1-row);
}
if( index >= size ){
row++;
index=row;
// remin= ( row==0 || row==numRows-1 ? jump: 2*(numRows-1-row) ) ;
}
PS:
char *s
可以用strlen算長度
我每次都忘記了....
----------------------------
SyntaxHighlighter 又不能用了FFFFFFFFFFF
char* convert(char* s, int numRows) {
int size= strlen(s);
//printf("%d",size);
if(numRows == 1 || size==1) return s;
int jump = numRows *2 -2;
//char *ans=(char*)malloc(sizeof(size)*sizeof(char));
char *ans;
//char ans[size];
//memset(ans,'\0',size);
//ans[size]='\0';
int row=0, remin=2*(numRows-1),index=0;
for(int count=0;count
ans[count]= s[index];
index=index+remin;
remin= ( row==0 || row==numRows-1 ? jump: jump-remin ) ;
if(index >= size){
row++;
index=row;
remin= ( row==0 || row==numRows-1 ? jump: 2*(numRows-1-row) ) ;
}
}
ans[size]='\0';
return ans;
}
-----------------------------
神人寫法:
簡單明瞭阿!!!!
char* convert(char* s, int numRows) { int n=strlen(s); char* a; int k=0; if(numRows==1 || n<=numRows)return s; for(int i=0;i
}
我後來發現我哪邊寫錯了....
char *ans=(char*)malloc(size*sizeof(char)+1);
我之前把size也用sizeof.....
char* convert(char* s, int numRows) {
int size=0;
while(s[size] !='\0')size++;
//int size= strlen(s);
//printf("%d",size);
if(numRows == 1 || size==1) return s;
int jump = numRows *2 -2;
char *ans=(char*)malloc(size*sizeof(char)+1);
//char *ans;
//char ans[size];
//memset(ans,'\0',size);
//ans[size]='\0';
int row=0, remin=2*(numRows-1),index=0;
for(int count=0;count
// printf("row= %d,s[index]=%c,index=%d,remin=%d\n",row,s[index],index,remin);
ans[count]= s[index];
index=index+remin;
remin= ( row==0 || row==numRows-1 ? jump: jump-remin ) ;
if(index >= size){
row++;
index=row;
remin= ( row==0 || row==numRows-1 ? jump: 2*(numRows-1-row) ) ;
}
}
ans[size]='\0';
return ans;
}
沒有留言:
張貼留言