# LeetCode 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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"
Explanation: This is the base case.


Example 2:

Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".


class Solution {
public:
string countAndSay(int n)
{
if (n == 1)
return "1";
string pre = countAndSay(n – 1);
string ans = "";
int i = 0, j;
while (i < pre.size()) {
j = i + 1;
while (j < pre.size() && pre[j] == pre[i])
j++;
ans += to_string(j – i) + pre.substr(i, 1);
i = j;
}
return ans;
}
};

# LeetCode Valid Sudoku

Determine if a 9×9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

1. Each row must contain the digits 1-9 without repetition.
2. Each column must contain the digits 1-9 without repetition.
3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: true


Example 2:

Input:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being
modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.


Note:

• A Sudoku board (partially filled) could be valid but is not necessarily solvable.
• Only the filled cells need to be validated according to the mentioned rules.
• The given board contain only digits 1-9 and the character '.'.
• The given board size is always 9x9.

class Solution {
public:
bool isValidSudoku(vector<vector<char> >& board)
{
int m = board.size();
if (m != 9)
return false;
for (int i = 0; i < m; i++) { // 行
int n = board[i].size();
if (n != 9)
return false;
vector<int> rows(n, 0);
for (int j = 0; j < n; j++) {
if (board[i][j] != ‘.’) {
rows[board[i][j] – ‘1’]++;
if (rows[board[i][j] – ‘1’] > 1)
return false;
}
}
}
for (int j = 0; j < m; j++) { //列
vector<int> cols(m, 0);
for (int i = 0; i < m; i++) {
if (board[i][j] != ‘.’) {
cols[board[i][j] – ‘1’]++;
if (cols[board[i][j] – ‘1’] > 1)
return false;
}
}
}
for (int i = 0; i < m; i += 3) { // 小方格
for (int j = 0; j < m; j += 3) {
vector<int> cubes(m, 0);
for (int k = 0; k < m; k++) {
if (board[i + k / 3][j + k % 3] != ‘.’) {
cubes[board[i + k / 3][j + k % 3] – ‘1’]++;
if (cubes[board[i + k / 3][j + k % 3] – ‘1’] > 1)
return false;
}
}
}
}
return true;
}
};

class Solution {
public:
bool isValidSudoku(vector<vector<char> >& board)
{
int m = 9;
vector<vector<int> > rows(9, vector<int>(9, 0)), cols(9, vector<int>(9, 0)), cubes(9, vector<int>(9, 0));
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (board[i][j] != ‘.’) {
int num = board[i][j] – ‘0’ – 1;
int k = i / 3 * 3 + j / 3;
if (rows[i][num] > 0 || cols[j][num] > 0 || cubes[k][num] > 0)
return false;
rows[i][num] = cols[j][num] = cubes[k][num] = 1;
}
}
}
return true;
}
};

class Solution {
public:
bool IsRepeat(vector<int>& flag, char c) {
if (c == '.')return false;
int val = c - '0';
if (flag[val] > 0)return true;
++flag[val];
return false;
}
bool isValidSudoku(vector<vector<char>>& board) {

vector<int> row_flag(10, 0), col_flag(10, 0), box_flag(10, 0);
for (int i = 0; i < 9; ++i) {
fill(row_flag.begin(), row_flag.end(), 0);
fill(col_flag.begin(), col_flag.end(), 0);

for (int j = 0; j < 9; ++j) {

int box_row_start = i / 3 * 3, box_col_start = i % 3 * 3;
int	box_row_offset = j / 3, box_col_offset = j % 3;
int box_row = box_row_start + box_row_offset, box_col = box_col_start + box_col_offset;

if ((box_row == 0 && (box_col == 0 || box_col == 3 || box_col == 6)) ||
(box_row == 3 && (box_col == 0 || box_col == 3 || box_col == 6)) ||
(box_row == 6 && (box_col == 0 || box_col == 3 || box_col == 6)))fill(box_flag.begin(), box_flag.end(), 0); // 小方块左上角

char rowc = board[i][j], colc = board[j][i], boxc = board[box_row][box_col];
if (IsRepeat(row_flag, rowc) || IsRepeat(col_flag, colc) || IsRepeat(box_flag, boxc))return false;

}
}
return true;
}
};

# LeetCode Implement strStr()

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


Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

class Solution {
public:
int strStr(string haystack, string needle)
{
int n1 = haystack.size(), n2 = needle.size();
if (n2 > n1)
return -1;
for (int i = 0; i < n1 – n2 + 1; i++) {
bool found = true;
for (int j = 0; j < n2; j++) {
if (needle[j] != haystack[i + j]) {
found = false;
break;
}
}
if (found)
return i;
}
return -1;
}
};

class Solution {
public:
void getNextVal(vector<int>& nextval, string t)
{
int n = t.size();
nextval.resize(n);
nextval[0] = -1;
int j = 0, k = -1;
while (j < n – 1) {
if (k == -1 || t[j] == t[k]) {
j++;
k++;
if (t[j] != t[k])
nextval[j] = k;
else
nextval[j] = nextval[k];
}
else
k = nextval[k];
}
}
int strStr(string haystack, string needle)
{
if (needle == "")
return 0;
int n1 = haystack.size(), n2 = needle.size();
if (n2 > n1)
return -1;
vector<int> nextval;
getNextVal(nextval, needle);
int i = 0, j = 0;
while (i < n1 && j < n2) {
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
}
else
j = nextval[j];
}
if (j >= n2)
return i – n2;
else
return -1;
}
};

（t[0,…,j]的前缀要以t[0]开头，后缀要以t[j]结尾，但都不能完全等于t[0,…,j]，即前缀不能以t[j]结尾，后缀不能以t[0]开头。）

$$next[j]=\begin{cases} \max\{k|0<k<j|t_0t_1…t_{k-1}==t_{j-k}t_{j-k+1}…t_{j-1}\}, & \mbox{if this set is nonempty}\\-1, & \mbox{if }j==0\\ 0, & \mbox{otherwise}\end{cases}$$

//优化过后的next 数组求法
void GetNextval(char* p, int next[])
{
int pLen = strlen(p);
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen – 1) {
//p[k]表示前缀，p[j]表示后缀
if (k == -1 || p[j] == p[k]) {
++j;
++k;
//较之前next数组求法，改动在下面4行
if (p[j] != p[k])
next[j] = k; //之前只有这一行
else //因为不能出现p[j] = p[ next[j ]]，所以当出现时需要继续递归，k = next[k] = next[next[k]]
next[j] = next[k];
}
else {
k = next[k];
}
}
}

class Solution {
public:
vector<int> GetNext(string s) {
int n = s.size();
vector<int> next(n, 0);
next[0] = -1;
int i = 0, j = -1;
while (i < n - 1) {
if (j == -1 || s[i] == s[j]) {
++i;
++j;
next[i] = j;
}
else {
j = next[j];
}
}
return next;
}
int strStr(string haystack, string needle) {
if (needle == "")return 0;
vector<int> next = GetNext(needle);
int m = haystack.size(), n = needle.size();
if (n > m)return -1;
int i = 0, j = 0;
while (i < m&&j < n) {
if (j == -1 || haystack[i] == needle[j]) {
++i;
++j;
}
else {
j = next[j];
}
}
if (j == n)return i - n;
else return -1;
}
};


# LeetCode Divide Two Integers

29. Divide Two Integers

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.


Example 2:

Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -2.


Note:

• Both dividend and divisor will be 32-bit signed integers.
• The divisor will never be 0.
• Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

class Solution {
public:
int divide(int dividend, int divisor)
{
if (divisor == 0)
return INT_MAX;
if (divisor == -1 && dividend == INT_MIN)
return INT_MAX;
unsigned int divd = dividend, divr = divisor;
if (dividend < 0)
divd = -divd; // 先都转换为正数，方便处理
if (divisor < 0)
divr = -divr;
int ans = 0;
while (divd >= divr) {
unsigned long long tmp = divr; // 注意类型，防止溢出
int p = 0;
while (divd >= tmp) {
tmp <<= 1;
p++;
}
ans += 1 << (p – 1);
divd -= divr << (p – 1);
}
int sign = dividend ^ divisor; // 首位为符号位，如果符号相同，异或之后为正数
return sign >= 0 ? ans : -ans;
}
};

P.S.一直以来对数论的题都没底，这次在将负数转换为正数时也花了不少时间。

// (a)_2 = 1111 1111 1111 1111 1111 1111 1100 0010; (a)_10 = -62;
int a = -62;
// (b)_2 = 1111 1111 1111 1111 1111 1111 1100 0010; (b)_10 = 4294967234;
unsigned int b = a;
// (b)_2 = 0000 0000 0000 0000 0000 0000 0011 1110; (b)_10 = 62;
b = -b;

class Solution {
public:
int divide(int dividend, int divisor) {

if (dividend == INT_MIN && divisor == -1)return INT_MAX;
if (dividend == INT_MIN && divisor == 1)return INT_MIN;

unsigned int a = dividend, b = divisor;
if (dividend < 0)
a = (~a+1);
if (divisor < 0)
b = (~b+1);

int ans = 0;
while (a >= b) {
int p = 0;
int tmp = b;
while (a > tmp && tmp < INT_MAX / 2) {
tmp <<= 1;
++p;
}
if (p > 0) {
ans += (1 << (p - 1));
a -= (tmp >> 1);
}
else if (p == 0) {
if (a >= tmp) {
++ans;
a -= tmp;
}
}
}

int sign = dividend ^ divisor;
if (sign >= 0)return ans;
else return -ans;
}
};

# LeetCode Remove Element

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.


Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
if (nums.size() == 0)
return 0;
if (nums.size() == 1)
return (nums[0] != val) ? 1 : 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == val) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[j] != val) {
nums[i] = nums[j];
nums[j] = val;
break;
}
}
}
}
if (nums[0] == val)
return 0;
else {
int i;
for (i = nums.size() – 1; i >= 0; i–)
if (nums[i] != val)
break;
return i + 1;
}
}
};

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size(), i = -1;
for (int j = 0; j < n; ++j) {
if (nums[j] != val)nums[++i] = nums[j];
}
return i + 1;
}
};