6. ZigZag Conversion
来源:互联网 发布:百度云盘mac不可用 编辑:程序博客网 时间:2024/06/05 19:30
题目:
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 R
And 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".
思路:
1. 获取字符串长度,开辟一个新的等长度的空间。
2. 当为NULL/“”的时候,或者nRows为1的时候,直接返回s本身。
以(2*nRows-2)为周期个数获取列col.
3. 先打出第一行的数组,并复制到新空间中。
打印出中间的数,注意的时候循环的列值要col+1,并赋值到新空间。
打印出最后一行,即是赋值最后一行的数据到新开辟的空间。(每次赋值,都判断下是否超出了最大长度)
注意:
leetcode调试的时候,发现run code可以,但是submit solution不行,但是结果都是没有错,两者运行结果一样,但是submit solution就是会报错。
后来发现是 Output Limit Exceeded,所以用于调试的输出不能太多,否则影响提交。
代码:
char* convert(char* s, int numRows) { int i=0,j=0,length=0; int cycle=2*numRows-2; int tmp,col=0; int endStart=numRows-1; //s is NULL if(s==NULL) { return NULL; } if(s[0]=='\0') { return s; } //Get the total length while(s[i++]!='\0') { length++; } if(numRows==1) { //Only one line //printf("The numRows is 1\n"); return s; } char* ret=(char *)malloc(sizeof(char)*(length+1)); int SUB=0; tmp=length%(cycle); if(tmp!=0) { col=length/cycle+1; } else { col=length/cycle; } //printf("The length is %d, col is %d \n",length,col); //First to print the first line for(j=0;j<col;j++) { int sub=j*cycle; if(sub<length) { ret[SUB++]=s[sub]; //printf("Line 34: %c\n",s[sub]); } } //print the middle lines int start=0; for(i=1;i<numRows-1;i++) { if(start==0) { ret[SUB++]=s[i]; //printf("Line 45: %c\n",s[i]); } for(j=1;j<=col;j++) //Must consider the = { int sub1=j*cycle-i; int sub2=j*cycle+i; if(sub1<length) { ret[SUB++]=s[sub1]; //printf("Line 54: %c\n",s[sub1]); } else { start=0; break; } if(sub2<length) { ret[SUB++]=s[sub2]; //printf("Line 65: %c\n",s[sub2]); } else { start=0; break; } } start=0; } //print the last line for(i=0;i<col;i++) { int sub=endStart+i*cycle; if(sub<length) { ret[SUB++]=s[sub]; //printf("Line 82: %c\n",s[sub]); } else { break; } } ret[SUB]='\0'; return ret;}
- LeetCode 6. ZigZag Conversion
- LeetCode --- 6. ZigZag Conversion
- LeetCode 6.ZigZag Conversion
- [Leetcode] 6. ZigZag Conversion
- 6.ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 【leetcode】6. ZigZag Conversion
- 6.ZigZag Conversion
- 6. ZigZag Conversion
- 6.ZigZag Conversion
- [LeetCode] 6.ZigZag Conversion
- LeetCode - 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6.ZigZag Conversion(93.10%)
- 6. ZigZag Conversion
- [leetcode] 6. ZigZag Conversion
- Java 基础 软件的开发周期
- JS学习(一)
- lang包的功能
- 记录历史时刻:hdoop完全分布式安装配置完成
- 妙曲vim
- 6. ZigZag Conversion
- android四大组件--ContentProvider详解
- hduoj1115
- Javo 基础 流的分类
- linux 添加一个系统调用
- UVa 12210 - A Match Making Problem
- R tutorial 02 - Operators 运算元
- python django paginator分页
- String、StringBuffer与StringBuilder之间区别