2014-10-17

来源:互联网 发布:腾讯视频网络电影合作 编辑:程序博客网 时间:2024/06/07 07:40

昨天帮老师搬办公室,然后就荒废了一天。罪过最过。主要是因为自己又放松了警惕。

早上把前天晚上留下的letcodetime给解决了。

竟然用了一个小时,easy的。!!!

如果是放在面试的话是妥妥被刷的节奏。

上题目

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   NA P L S I I GY   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".

题目的意思是把字符串竖着排下来,然后横着读过去。一开始没读懂,直接百度了题目的意思····

解题过程中主要还是边界问题。

因为当在波峰或者波谷的时候,每次要跨越两个对称轴,跟其他的元素不一样,所以要分开处理。

我就是在这个波峰和波谷的位置计算上面折腾太久了。

自己做出来后,看了网上其他人的答案,处理的方式都是一样的,要对波峰波谷分开处理。

没办法,脑袋瓜要开始训练了,不然去不了梦寐以求的公司啊。


上CODE。

import java.*;public class zigzag_convertion {public String convert(String s, int nRows) {String answer = "";if (nRows == 1)return s;for (int i = 0; i < nRows; ++i) {for (int j = i, time = 1; j < s.length();) {answer += s.substring(j, j + 1);if (i == 0 || i == nRows - 1)//在波峰或者波谷的时候,每次位置跨越两个对称轴j = j+(nRows-1) * 2;else {//其他位置的时候只要跨越一个对称轴j = j + ((nRows - 1) * time - j) * 2;time++;}}// System.out.print(answer+'\n');}return answer;}public static void main(String[] args) {System.out.print(new zigzag_convertion().convert("abcdef", 3));<span style="white-space:pre"></span>//时间空间复杂度是O(n),有没有可能把空间复杂度减少到O(1)呢?<span style="white-space:pre"></span>}}




0 0
原创粉丝点击