3. Longest Substring Without Repeating Characters (medium)
最长的无重复的子字符串
Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 vector<int> dict(256, -1); 5 int start = -1, res = 0; 6 for (int i = 0; i < s.size(); ++i) { 7 if (dict[s[i]] > start) 8 start = dict[s[i]]; 9 res = max(res, i - start); 10 dict[s[i]] = i; 11 } 12 return res; 13 } 14 };
5. Longest Palindromic Substring (medium)
最长的对称子字符串
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 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 string res; 5 int cnt = 0; 6 for (int i = 0; i < s.size();) { 7 int left = i, right = i; 8 while (right + 1 < s.size() && s[right + 1] == s[i]) 9 ++right; 10 i = right + 1; 11 while (left > 0 && right < s.size() - 1 && s[left - 1] == s[right + 1]) { 12 --left; 13 ++right; 14 } 15 if (right - left + 1 > cnt) { 16 cnt = right - left + 1; 17 res = s.substr(left, cnt); 18 } 19 } 20 return res; 21 } 22 };
6. ZigZag Conversion (medium)
以zigzag顺序重排字符串
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".
1 // numRows == 1时,不能加减 2 class Solution { 3 public: 4 string convert(string s, int numRows) { 5 if (1 == numRows) return s; // 6 vector<string> tmp(numRows, ""); 7 for (int i = 0, j = 0, step = 1; i < s.size(); j += step) { 8 tmp[j].push_back(s[i++]); 9 if (j == 0) step = 1; 10 else if (j == numRows - 1) step = -1; 11 } 12 for (int i = 1; i < numRows; ++i) 13 tmp[0] += tmp[i]; 14 return tmp[0]; 15 } 16 };
8. String to Integer (atoi) (medium)
字符串转数字
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. Update (2015-02-10): The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition. spoilers alert... click to show requirements for atoi. Requirements for atoi: The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 long res = 0; 5 int i = 0, sign = 1; 6 while (i < str.size() && str[i] == ‘ ‘) 7 ++i; 8 if (str[i] == ‘+‘ || str[i] == ‘-‘) 9 sign = str[i++] == ‘+‘ ? 1 : -1; 10 for (; i < str.size() && str[i] >= ‘0‘ && str[i] <=‘9‘; ++i) { 11 res = res*10 + str[i] - ‘0‘; 12 if (res*sign > INT_MAX) 13 return INT_MAX; 14 else if (res*sign < INT_MIN) 15 return INT_MIN; 16 } 17 return (int)(res*sign); 18 } 19 };
12. Integer to Roman (medium)
数字转罗马数字
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
1 class Solution { 2 public: 3 string intToRoman(int num) { 4 string M[] = {"", "M", "MM", "MMM"}; 5 string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 6 string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 7 string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 8 return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; 9 } 10 };
13. Roman to Integer (easy)
罗马数字转普通数字
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 unordered_map<char, int> T = { { ‘I‘ , 1 }, 5 { ‘V‘ , 5 }, 6 { ‘X‘ , 10 }, 7 { ‘L‘ , 50 }, 8 { ‘C‘ , 100 }, 9 { ‘D‘ , 500 }, 10 { ‘M‘ , 1000 } }; 11 int sum = T[s.back()]; 12 for (int i = s.length() - 2; i >= 0; --i) { 13 if (T[s[i]] < T[s[i + 1]]) 14 sum -= T[s[i]]; 15 else 16 sum += T[s[i]]; 17 } 18 return sum; 19 } 20 };
14. Longest Common Prefix (easy)
最长的公共前缀
Write a function to find the longest common prefix string amongst an array of strings.
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string>& strs) { 4 if (strs.empty()) return ""; 5 string str1 = strs[0]; 6 for (int i = 1; i < strs.size(); ++i) { 7 string str2 = strs[i]; 8 int index = 0; 9 for (; str1[index] == str2[index]; ++index); 10 str1 = str1.substr(0, index); 11 } 12 return str1; 13 } 14 };
17. Letter Combinations of a Phone Number (medium) #
手机键盘输入组合
Given a digit string, 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. Input:Digit string "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.
1 class Solution { 2 public: 3 vector<string> letterCombinations(string digits) { 4 if (digits.empty()) return vector<string>(); 5 vector<string> keyBoard = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 6 vector<string> res; 7 res.push_back(""); 8 for (auto num : digits) { 9 vector<string> tmp; 10 for (auto cur : res) { 11 for (auto newChar : keyBoard[num - ‘0‘]) 12 tmp.push_back(cur + newChar); 13 } 14 res.swap(tmp); 15 } 16 return res; 17 } 18 };
20. Valid Parentheses (easy)
判断()[]{}格式
Given a string containing just the characters ‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘ and ‘]‘, determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
1 class Solution { 2 public: 3 bool isValid(string s) { 4 stack<char> st; 5 for (auto c : s) { 6 if (c == ‘(‘) 7 st.push(‘)‘); 8 else if (c == ‘[‘) 9 st.push(‘]‘); 10 else if (c == ‘{‘) 11 st.push(‘}‘); 12 else if (!st.empty() && st.top() == c) 13 st.pop(); 14 else 15 return false; 16 } 17 return st.empty(); 18 } 19 };
22. Generate Parentheses (medium) #
n个括号对的所有组合
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: [ "((()))", "(()())", "(())()", "()(())", "()()()" ]
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string> res; 5 string tmp; 6 helper(res, tmp, n, 0); 7 return res; 8 } 9 void helper(vector<string>& res, string tmp, int left, int right) { 10 if (left == 0 && right == 0) { 11 res.push_back(tmp); 12 return; 13 } 14 if (left > 0) 15 helper(res, tmp + "(", left - 1, right + 1); 16 if (right > 0) 17 helper(res, tmp + ")", left, right - 1); 18 } 19 };
28. Implement strStr() (easy)
字符串查找
Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "hello", needle = "ll" Output: 2 Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1
1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 if (needle.empty()) 5 return 0; 6 int res, i, j; 7 for (res = 0; res <= (int)haystack.size() - (int)needle.size(); ++res) { 8 for (i = res, j = 0; j < needle.size() && haystack[i] == needle[j]; ++i, ++j); 9 if (j == needle.size()) 10 return res; 11 } 12 return -1; 13 } 14 };
28. Implement strStr() (easy)