# LeetCode Longest Common Prefix

LeetCode Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.

class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0)return "";
int max_common = INT_MAX;
string longest_common = "";
for (int i = 0; i < strs.size(); i++)
if (strs[i].size() < max_common)
max_common = strs[i].size();
for (int i = 0; i < max_common; i++) {
for (int j = 1; j < strs.size(); j++) {
if (strs[j][i] != strs[0][i])
return longest_common;
}
longest_common += strs[0][i];
}
return longest_common;
}
};


# LeetCode Roman to Integer

LeetCode Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

class Solution {
public:
int romanToInt(string s) {
vector<int> nums = { 1,4,5,9,10,40,50,90,100,400,500,900,1000 };
vector<string> symbol = { "I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M" };
int ans = 0;
for (int i = nums.size() - 1; i >= 0; i--) {
int sz = symbol[i].size();
while (s.size() >= sz&&s.substr(0, sz) == symbol[i]){
ans += nums[i];
s = s.substr(sz);
}
}
return ans;
}
};


# LeetCode Integer to Roman

LeetCode Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.

class Solution {
public:
string work(int num, string cur){
if (num >= 1000)
return work(num - 1000, cur + "M");
if (num >= 500){
if (num >= 900)
return work(num - 900, cur + "CM");
return work(num - 500, cur + "D");
}
if (num >= 100){
if (num >= 400)
return work(num - 400, cur + "CD");
return work(num - 100, cur + "C");
}
if (num >= 50){
if (num >= 90)
return work(num - 90, cur + "XC");
return work(num - 50, cur + "L");
}
if (num >= 10){
if (num >= 40)
return work(num - 40, cur + "XL");
return work(num - 10, cur + "X");
}
if (num >= 5){
if (num >= 9)
return work(num - 9, cur + "IX");
return work(num - 5, cur + "V");
}
if (num < 5){
if (num >= 4)
return work(num - 4, cur + "IV");
while (num > 0){
cur += "I";
num--;
}
return cur;
}
}
string intToRoman(int num) {
return work(num, "");
}
};


class Solution {
public:
string intToRoman(int num) {
vector<int> nums = { 1,4,5,9,10,40,50,90,100,400,500,900,1000 };
vector<string> symbol = { "I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M" };
string ans = "";
for (int i = nums.size() - 1; i >= 0; i--){
while (num >= nums[i]){
ans += symbol[i];
num -= nums[i];
}
}
return ans;
}
};


# LeetCode Container With Most Water

LeetCode Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.

class Solution {
public:
int maxArea(vector<int>& height) {
int mA = 0, i = 0, j = height.size() - 1;
while (i != j)
{
int cur = min(height[i], height[j])*(j - i);
if (cur > mA)
mA = cur;
if (height[i] < height[j])
i++;
else
j--;
}
return mA;
}
};


# LeetCode Decode Ways

LeetCode Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26


Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.

DP转移公式如下：

class Solution {
public:
int numDecodings(string s) {
if (s == "" || s[0] == '0')return 0;
s = "^" + s;
int n = s.size();
vector<int> dp(n, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i < n; i++)
{
if (s[i] >= '1' && s[i] <= '9')
dp[i] += dp[i - 1];
if ((s[i - 1] == '1' && s[i] >= '0' && s[i] <= '9') || (s[i - 1] == '2' && s[i] >= '0' && s[i] <= '6'))
dp[i] += dp[i - 2];
}
return dp[n - 1];
}
};


# LeetCode Distinct Subsequences

LeetCode Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.

DP转移公式如下：

class Solution {
public:
int numDistinct(string s, string t) {
if (s == "")
return 0;
if (t == "")
return 1;
s = "^" + s;
t = "^" + t;
int n = s.size(), m = t.size();
vector<vector<int>> dp(n, vector<int>(m, 0));
for (int i = 0; i < n; i++)
dp[i][0] = 1; // '*' -> '' 1 sub
for (int i = 1; i < n; i++)
{
for (int j = 1; j < m; j++)
{
dp[i][j] = dp[i - 1][j];
if (s[i] == t[j])
dp[i][j] += dp[i - 1][j - 1];
}
}
return dp[n - 1][m - 1];
}
};


# LeetCode Palindrome Partitioning II

LeetCode Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
for (int i = 0; i < n; i++)
dp[i][i] = true;
vector<int> cut(n, 0); // # of cut for s[0,j]
for (int j = 0; j < n; j++)
{
cut[j] = j; // set maximum # of cut
for (int i = 0; i <= j; i++)
{
if (s[i] == s[j] && (j - i <= 1 || dp[i + 1][j - 1]))
{
dp[i][j] = true;
if (i > 0) // if need to cut, add 1 to the previous cut[i-1]
cut[j] = min(cut[j], cut[i - 1] + 1);
else // if [0...j] is palindrome, no need to cut
cut[j] = 0;
}
}
}
return cut[n - 1];
}
};


.......aba...
|<-X->| ^
|<---Y-->|


class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<int> cuts(n + 1, 0); // cuts[i] 表示前i个字符切成回文子串，最少的刀数
for(int i = 0; i <= n; ++i) cuts[i]  = i - 1;
for(int i = 0; i < n; ++i) {
for(int j = 0; i - j >= 0 && i + j < n && s[i - j] == s[i + j]; ++j) // 最后一个是奇数长回文子串
cuts[i + j + 1] = min(cuts[i + j + 1], cuts[i - j] + 1);
for(int j = 1; i - j + 1 >= 0 && i + j < n && s[i - j + 1] == s[i + j]; ++j) // 最后一个是偶数长回文子串
cuts[i + j + 1] = min(cuts[i + j + 1], cuts[i - j + 1] + 1);
}
return cuts[n];
}
};


# LeetCode Palindrome Number

LeetCode Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.

Some hints:Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.

class Solution {
public:
bool isPalindrome(int x) {
if (x < 10)
return x >= 0;
if (x % 10 == 0)
return false;
int y = 0;
while (x > y)
{
y = y * 10 + x % 10;
if (x == y) //76567
return true;
x /= 10;
if (x == y) //765567
return true;
}
return false;
}
};


# LeetCode String to Integer (atoi)

LeetCode String to Integer (atoi)
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.

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.

If the converted value would be out of the range of representable values by an int, it causes undefined behavior. Seestrtol for a more robust cross-platform alternative when this is a possibility.

class Solution {
public:
int myAtoi(string str) {
int i = 0;
while (i < str.size() && str[i] == ' ')
i++;
string tmp = str.substr(i);
if (tmp.size() == 0 || (tmp.size() == 1 && (tmp[0] < '0' || tmp[0] > '9')))
return 0;
string digits = (tmp[0] == '-' || tmp[0] == '+') ? tmp.substr(1) : tmp;
double ans = 0;
for (int i = 0; i < digits.size(); i++)
if (digits[i] < '0' || digits[i] > '9')
break;
else
ans = ans * 10 + (digits[i] - '0');
ans = (tmp[0] == '-') ? -ans : ans;
if (ans > INT_MAX)
return INT_MAX;
else if(ans < INT_MIN)
return INT_MIN;
else return ans;
}
};


# LeetCode Reverse Integer

LeetCode Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.

class Solution {
public:
int reverse(int x) {
unsigned int y = (x > 0) ? x : -x;
double ans = 0;
while (y)
{
ans = ans * 10 + (y % 10);
y = y / 10;
}
if (ans > INT_MAX)
return 0;
return x < 0 ? -ans : ans;
}
};