第十七周(ZigZag Conversion )
目录:
- 本周完成题目
- 主要过程思路
- 相关代码
一、本周完成题目
本周共完成2道题目,1道Medium,1道Easy。
具体完成题目及难度如下表:
# | Title | Difficulty |
---|---|---|
6 | ZigZag Conversion | Medium |
7 | Reverse Integer | Easy |
题目内容
1、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 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”.
题目大意:给一个字符串,按Z字形返回一个新顺序的字符串。
2、Reverse Integer
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
题目大意:给一个字符串,返回最长的回文子字符串。
二、主要过程思路
1、ZigZag Conversion:
本问题主要需要关注的点就是ZigZag具体是什么样的。这一点上我参考了下面这个解释。
https://discuss.leetcode.com/topic/22925/if-you-are-confused-with-zigzag-pattern-come-and-see
/*n=numRows
Δ=2n-2 1 2n-1 4n-3
Δ= 2 2n-2 2n 4n-4 4n-2
Δ= 3 2n-3 2n+1 4n-5 .
Δ= . . . . .
Δ= . n+2 . 3n .
Δ= n-1 n+1 3n-3 3n-1 5n-5
Δ=2n-2 n 3n-2 5n-4
*/
也就是说我们需要实现上面的这种访问顺序。这里使用一个for循环,逐行加入字符到新的字符串中。
对于每一行,首先访问第i个值,之后增加(numRows-i-1)*2,2i(1隔1增加)。当访问的值大于字符串长度的时候就停止对于该行的访问。直到numRows行都访问结束。
2、Reverse Integer:
本题比较简单。只需要每次对于x求余,然后加到目标整数中即可。不过需要注意数据溢出的问题。如果超过了范围则返回0。
三、相关代码
ZigZag Conversion
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> visit(256, -1);
int start=-1,result=0;
for(int i=0;i<s.size();i++){
if(visit[s[i]]>start){
start=visit[s[i]];
}
result=max(result,i-start);
visit[s[i]]=i;
}
return result;
}
};
Reverse Integer
class Solution {
public:
int reverse(int x) {
long result=0;
while(x!=0){
result=x%10+result*10;
x=x/10;
if(result<INT_MIN || result>INT_MAX)
return 0;
}
return result;
}
};