6. 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字形,其实就是把一维字符串从上到下,从下到上这样往复排列,然后把每一行拼接起来。
代码实现
class Solution {
public:
string convert(string s, int numRows) {
int slen = s.length();
string res;
if(slen <= numRows || numRows <= 1) return s;
vector<vector<char>> str(slen);
bool dir = true;
int ind = 0;
for(int i = 0; i < slen; i++) {
str[ind].push_back(s[i]);
if(ind >= numRows - 1) {
dir = false;
ind--;;
}
else {
if(!dir && ind) ind--;
else{ ind++; dir = true; }
}
}
for(int j = 0; j < numRows; j++)
res += string(str[j].begin(), str[j].end());
return res;
}
};
38. Count and Say
题目描述
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …
- 1 is read off as “one 1” or 11.
- 11 is read off as “two 1s” or 21.
- 21 is read off as “one 2, then one 1” or 1211.
- Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
这道题目的题目意思比较难费解,其实就是这样的:
如果n =1, 那么就是“1”。 n=2,对前面的“1”进行描述就是一个1,那就是“11”。n = 3的时候,对“11”进行描述就是“21”,前面一个数字表示这个数字连续有几个,后面一个数字表示是什么数字。然后“21”就是“1211”。下一个就是“111221”,再下一个就是“312211”
代码实现
class Solution {
public:
string countAndSay(int n) {
string res = "1";
int count = 0;
for(int i = 0; i < n-1; i++) {
int fstlen = res.length();
string tmp;
for(int j = 0; j < fstlen; j++) {
count = 1;
while(j+1 < fstlen && res[j] == res[j+1]) {j++; count++;}
tmp.push_back(char('0'+count));
tmp.push_back(res[j]);
}
//cout << tmp << endl;
res = tmp;
}
return res;
}
};