5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
提示:start遍历string,left = right = start,记录以start为中心(如果有重复,start指向最左数)的回文字符串长度。
答案:
class Solution { public: std::string longestPalindrome(std::string s) { if (s.size() < 2) return s; int len = s.size(), max_left = 0, max_len = 1, left, right; for (int start = 0; start < len && len - start > max_len / 2;) { left = right = start; while (right < len - 1 && s[right + 1] == s[right]) ++right; start = right + 1; while (right < len - 1 && left > 0 && s[right + 1] == s[left - 1]) { ++right; --left; } if (max_len < right - left + 1) { max_left = left; max_len = right - left + 1; } } return s.substr(max_left, max_len); } };
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
提示:找index规律,interval = 2 *(numRows - 1),第一行与最后一行相距interval,中间行相距在2与4x-6之间徘徊
答案:
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) { return s; } std::string res; res.reserve(s.size()); // print first row int interval = 2 * (numRows - 1); for (int i = 0; i < s.length(); i += interval) { res += s[i]; } // print middle rows (conditionally) for (int row = 1; row < numRows - 1; row ++) { for (int i = row, j = 0; i < s.length(); j += interval, i = j - i) { res += s[i]; } } // print last row (conditionally) if (numRows > 1) { for (int i = numRows - 1; i < s.length(); i += interval) { res += s[i]; } } return res; } };14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
提示:拿出第一个字符串的第一个字符,与后面的每一个字符串比较,不同就返回。
答案:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.empty()) { return ""; } for (int i = 0; i < strs[0].size(); ++i) { // iterate through each character in base for (int j = 1; j < strs.size(); ++j) { if (strs[0][i] != strs[j][i]) { return strs[0].substr(0, i); } } } return strs[0]; } };
17. Letter Combinations of a Phone Number
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
提示:string数组代替map,temp临时保存上一循环res。注意res.clear()情况。
答案:
class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; res.push_back(""); for (int i = 0; i < digits.size(); i++) { vector<string> temp; string chars = charmap[digits[i] - '0']; for (int c = 0; c < chars.size();c++) for (int j = 0; j < res.size();j++) temp.push_back(res[j]+chars[c]); res = temp; } if ((res.size()==1)&&(res[0] == "")) res.clear(); return res; } };
20. Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 4:
Input: "([)]" Output: false
提示:使用stack,如果是左括号,入栈(把右括号入栈可以减少代码行),如果是右括号,比较后出栈
答案:
class Solution {
public:
bool isValid(string s) {
//empty
stack<char> stk;
for(char c : s){
if (c == '(')
stk.push(')');
else if (c == '{')
stk.push('}');
else if (c == '[')
stk.push(']');
else if (stk.empty() || stk.top() != c)
return false;
else stk.pop();
}
return stk.empty();
}
};
22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
提示:递归,使用left = right = n,分别保存左、右括号剩余个数。
答案:
class Solution { private: void helper(vector<string> & res, string str, int left, int right){ if(left == 0 && right == 0){ res.push_back(str); return; } if(left > 0) helper(res, str + "(", left - 1, right); if(right > left) helper(res, str + ")", left, right - 1); } public: vector<string> generateParenthesis(int n) { vector<string> ret; helper(ret, "", n, n); return ret; } };
38. Count and Say
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
From the examples you can see, the (i+1)th sequence is the "count and say" of the ith sequence!
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211
From the examples you can see, the (i+1)th sequence is the "count and say" of the ith sequence!
提示:迭代或者递归。主要为for语句遍历res,cout计数,while语句遍历重复数。
答案:
class Solution { public: string countAndSay(int n) { if (n == 0) return ""; string res = "1"; while (--n) { string cur = ""; for (int i = 0; i < res.size(); i++) { int count = 1; while ((i + 1 < res.size()) && (res[i] == res[i + 1])){ count++; i++; } cur += to_string(count) + res[i]; } res = cur; } return res; } };
string countAndSay(int n) { if (n == 1){return "1";} if (n == 2){return "11";} string result = countAndSay(n-1); string newresult = ""; int count = 1; for(int i = 1; i < result.size(); ++i){ if(result[i]!=result[i-1]){ newresult.push_back('0'+count); newresult.push_back(result[i-1]); count = 1; }else{ count++; } if(i == result.size()-1){ newresult.push_back('0'+count); newresult.push_back(result[i]); } } return newresult; }
58. Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World" Output: 5
提示:第一个while语句找到非‘ ’字符,第二个while语句计数
答案:
class Solution { public: int lengthOfLastWord(string s) { int len = 0, tail = s.length() - 1; while (tail >= 0 && s[tail] == ' ') tail--; while (tail >= 0 && s[tail] != ' ') { len++; tail--; } return len; } };
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
path = “/a/./b/../c/”, => “/a/c”
path = “/a/./b/c/”, => “/a/b/c”
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
提示:1、如果是空或者“.”,那么当前没有什么地址变动,地址栈不需要变动
2、如果是“..” 则需要出栈(如果栈为空则不操作)因为这是返回上级目录的符号
3、其他情况压栈
string&str表示把从输入流读入的字符串存放在这个字符串中(可以自己随便命名,str什么的都可以);
char delim表示遇到这个字符停止读入,在不设置的情况下系统默认该字符为'\n',也就是回车换行符(遇到回车停止读入)。
答案:
class Solution { public: string simplifyPath(string path) { string res, tmp; if(path.empty()) return res; vector<string> stk; stringstream ss(path); while(getline(ss,tmp,'/')) { if (tmp == "" or tmp == ".") continue; if(tmp != "..") stk.push_back(tmp); else if(!stk.empty()) stk.pop_back(); } for(auto str : stk) res += "/"+str; return res.empty() ? "/" : res; } };