ZigZag Conversion an interesting approach
2017-08-17 17:24
190 查看
问题描述
The string
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
解决方法
这道题我一直从n阶方阵与数组索引的关系上下手,没想到这个方法这么简单。
从串的索引0开始,一直到结尾,按正序遍历,将每个字符按照第0行放一个,第1行放一个......第numRow行放一个,第numRow-1行放一个,......第0行放一个..........这种循环来放字符。用变量incre来控制行之间的来回循环,直至串尾。
本解法抓住了只需打印每一行的串,而不需要知道每个字符的绝对位置,只需要相对位置(即前后顺序对就行)这个点,从而一举解决问题。
时间复杂度,0(n)
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".
解决方法
这道题我一直从n阶方阵与数组索引的关系上下手,没想到这个方法这么简单。
从串的索引0开始,一直到结尾,按正序遍历,将每个字符按照第0行放一个,第1行放一个......第numRow行放一个,第numRow-1行放一个,......第0行放一个..........这种循环来放字符。用变量incre来控制行之间的来回循环,直至串尾。
本解法抓住了只需打印每一行的串,而不需要知道每个字符的绝对位置,只需要相对位置(即前后顺序对就行)这个点,从而一举解决问题。
public String convert(String s, int numRows) { if(numRows<=1)return s; StringBuilder[] sb=new StringBuilder[numRows]; for(int i=0;i<sb.length;i++){ sb[i]=new StringBuilder(""); //init every sb element **important step!!!! } int incre=1; int index=0; for(int i=0;i<s.length();i++){ sb[index].append(s.charAt(i)); if(index==0){incre=1;} if(index==numRows-1){incre=-1;} index+=incre; } String re=""; for(int i=0;i<sb.length;i++){ re+=sb[i]; } return re.toString(); }
时间复杂度,0(n)
相关文章推荐
- 6. ZigZag Conversion
- 《Wavelet Theory:An elementary Approach With Applications》中关于例6.10的疑惑
- 6.ZigZag Conversion
- LeetCode(6) ZigZag Conversion
- 6. ZigZag Conversion
- <LeetCode><Easy> 6 ZigZag Conversion
- JavaWeb java.io.CharConversionException: Not an ISO 8859-1 character: xx
- Leetcode<6 ZigZag Conversion>解题报告
- leetcode ZigZag Conversion
- LeetCode ZigZag Conversion
- 【品读经典】 An Engineering Approach to Computer Networking (二)
- LeetCode每日一练(6) ZigZag Conversion C++版
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- leetcode[ZigZag Conversion]//待整理多种解法
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- Deploying Simulink Designs on Your DSP: An Accelerated Approach to Custom Implementation--from Matlab Digest