中文leetcode网址:link
resut = result * 10 + x % 10
x = x / 10
if x == 0:
return True
elif x < 0 or x % 10 == 0:
return False
else:
inverse_num = 0
while x > inverse_num:
inverse_num = inverse_num * 10 + x % 10
x = x // 10
if x == inverse_num or x == inverse_num // 10:
return True
else:
return False
class Solution:
def romanToInt(self, s: str) -> int:
processed = 0
result = 0
while processed < len(s):
if s[processed] == 'I':
if processed + 1 < len(s):
if s[processed+1] == 'V':
result += 4
processed += 1
elif s[processed+1] == 'X':
result += 9
processed += 1
else:
result += 1
else:
result += 1
elif s[processed] == 'X':
if processed + 1 < len(s):
if s[processed+1] == 'L':
result += 40
processed += 1
elif s[processed+1] == 'C':
result += 90
processed += 1
else:
result += 10
else:
result += 10
elif s[processed] == 'C':
if processed + 1 < len(s):
if s[processed+1] == 'D':
result += 400
processed += 1
elif s[processed+1] == 'M':
result += 900
processed += 1
else:
result += 100
else:
result += 100
elif s[processed] == 'V':
result += 5
elif s[processed] == 'L':
result += 50
elif s[processed] == 'D':
result += 500
elif s[processed] == 'M':
result += 1000
processed += 1
return result
if len(strs) == 0:
return ""
if len(strs) == 1:
return strs[0]
common_len = 0
while True:
if common_len > len(strs[0]) - 1:
return strs[0][:common_len]
tmp_char = strs[0][common_len]
for str_index in range(1, len(strs)):
if common_len > len(strs[str_index]) -1:
return strs[0][:common_len]
if strs[str_index][common_len] == tmp_char:
continue
else:
return strs[0][:common_len]
common_len += 1
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == 0:
return True
if len(s) % 2 == 1:
return False
buffer = []
left = ['{', '(', '[']
right = ['}', ')', ']']
pairs = {}
for i, j in zip(left, right):
pairs[i] = j
for i in range(len(s)):
if len(buffer) == 0:
if s[i] in left:
buffer.append(s[i])
else:
return False
elif s[i] in left:
buffer.append(s[i])
elif pairs[buffer[-1]] == s[i]:
buffer.pop()
continue
else:
return False
if len(buffer) == 0:
return True
else:
return False
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
result_list = ListNode()
p = result_list
p1 = l1
p2 = l2
while p1 is not None and p2 is not None:
if p1.val <= p2.val:
p.next = p1
p1 = p1.next
else:
p.next = p2
p2 = p2.next
p = p.next
while p1 is not None:
p.next = p1
p1 = p1.next
p = p.next
while p2 is not None:
p.next = p2
p2 = p2.next
p = p.next
return result_list.next
if p1 is not None:
p.next = p1
else:
p.next = p2
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
return_len = 1
for i in range(1, len(nums)):
if nums[i] != nums[return_len - 1]:
nums[return_len] = nums[i]
return_len += 1
return return_len
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
return_len = 0
for i in range(len(nums)):
if nums[i] != val:
if return_len != i:
nums[return_len] = nums[i]
return_len += 1
return return_len
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
for i in range(len(haystack) - len(needle) + 1):
is_same = True
for j in range(len(needle)):
if haystack[i + j] != needle[j]:
is_same = False
break
if is_same:
return i
return -1
class Solution:
def searchInsert(self, nums, target) -> int:
# 二分法
if nums[0] > nums[-1]:
order = 1
else:
order = 0
left = 0
right = len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] < target:
if order == 0:
left = middle + 1
else:
right = middle - 1
elif nums[middle] > target:
if order == 1:
left = middle + 1
else:
right = middle - 1
else:
return middle
return left
class Solution:
def countAndSay(self, n: int) -> str:
if n == 1:
return '1'
last_level = self.countAndSay(n - 1)
result = ''
continue_char = last_level[0]
continue_num = 1
for char in last_level[1:]:
if char == continue_char:
continue_num += 1
else:
result += str(continue_num) + continue_char
continue_char = char
continue_num = 1
result += str(continue_num) + continue_char
return result
pre = 0
maxAns = 0
for num in nums:
pre = max(pre + num, num)
maxAns = max(maxAns, pre)
return maxAns
st = self.Status()
st.isum = lSub.isum + rSub.isum
st.lsum = max(lSub.lsum, lSub.isum + rSub.lsum)
st.rsum = max(rSub.rsum, lSub.rsum + rSub.isum)
st.msum = max(max(lSub.msum, rSub.msum), lSub.rsum + rSub.lsum)
class Solution:
class Status:
def __init__(self, l=0, r=0, i=0, m=0):
self.lsum = l
self.rsum = r
self.isum = i
self.msum = m
def pushUp(self, l: Status, r: Status) -> Status:
st = self.Status()
st.isum = l.isum + r.isum
st.lsum = max(l.lsum, l.isum + r.lsum)
st.rsum = max(r.rsum, l.rsum + r.isum)
st.msum = max(max(l.msum, r.msum), l.rsum + r.lsum)
return st
def get(self, nums: List[int], l: int, r: int) -> Status:
if l == r:
return self.Status(nums[l], nums[l], nums[l], nums[l])
m = (l + r) // 2
lSub = self.get(nums, l, m) # type: Status
rSub = self.get(nums, m+1, r) # type: Status
return self.pushUp(lSub, rSub)
def maxSubArray(self, nums: List[int]) -> int:
return self.get(nums, 0, len(nums) - 1).msum
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
addToPre = 0
digits[-1] += 1
for i in range(len(digits) - 1, -1, -1):
if digits[i] < 10:
break
else:
digits[i] = 0
if i > 0:
digits[i - 1] += 1
else:
digits = [1] + digits
break
return digits
class Solution:
def addBinary(self, a: str, b: str) -> str:
res = ''
addToPre = 0
i, j = len(a) - 1, len(b) - 1
while i >= 0 or j >= 0:
cur = 0
if i >= 0:
cur += int(a[i])
if j >= 0:
cur += int(b[j])
cur += addToPre
if cur >= 2:
addToPre = 1
cur -= 2
else:
addToPre = 0
res = str(cur) + res
i -= 1
j -= 1
if addToPre == 1:
res = '1' + res
return res
mid ** 2 == x or (mid ** 2 < x and (mid + 1) ** 2 > x)
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
f1 = 1
f2 = 2
tmp_n = 3
while tmp_n <= n:
cur = f1 + f2
f1 = f2
f2 = cur
tmp_n += 1
return cur
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
p = head
cur = p
while p:
while p and cur.val == p.val:
p = p.next
cur.next = p
cur = p
return head
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
if nums1[m - 1] > nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
else:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
while n > 0:
nums1[n - 1] = nums2[n - 1]
n -= 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p is None and q is None:
return True
if p is None or q is None:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
return self.isSame(root.left, root.right)
def isSame(self, left: TreeNode, right: TreeNode) -> bool:
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return self.isSame(left.left, right.right) and self.isSame(left.right, right.left)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root is None:
return True
queue = [root, root]
while len(queue) > 0:
p, q = queue[:2]
queue = queue[2:]
if p is None and q is None:
pass
elif p is None or q is None:
return False
elif p.val != q.val:
return False
else:
queue.append(p.left)
queue.append(q.right)
queue.append(p.right)
queue.append(q.left)
return True
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for num in nums[1:]:
nums[0] ^= num
return nums[0]
class Solution:
def isPalindrome(self, s: str) -> bool:
p1 = 0
p2 = len(s) - 1
while p1 < p2:
if not self.check_available(s[p1]):
p1 += 1
continue
if not self.check_available(s[p2]):
p2 -= 1
continue
if s[p1].lower() != s[p2].lower():
return False
p1 += 1
p2 -= 1
return True
def check_available(self, char):
if 'A' <= char <= 'Z' or 'a' <= char <= 'z' or '0' <= char <= '9':
return True
return False
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
p = headA
len_A = 0
while p:
len_A += 1
p = p.next
p = headB
len_B =0
while p:
len_B += 1
p = p.next
dif = len_A - len_B
if dif >= 0:
p1 = headA
p2 = headB
else:
p1 = headB
p2 = headA
dif *= -1
while dif > 0:
p1 = p1.next
dif -= 1
while p1 and p2:
if p1 == p2:
return p1
p1 = p1.next
p2 = p2.next
return None
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
p1 = 0
p2 = len(numbers) - 1
while p1 < p2:
res = numbers[p1] + numbers[p2]
if res == target:
return [p1 + 1, p2 + 1]
elif res < target:
p1 += 1
else:
p2 -= 1
class Solution:
def majorityElement(self, nums: List[int]) -> int:
candidate = 0
count = 0
for num in nums:
if count == 0:
candidate = num
count = 1
elif candidate == num:
count += 1
else:
count -= 1
return candidate
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
nodelist = [root]
ans = 0
while len(nodelist) > 0:
sz = len(nodelist)
while sz > 0:
node = nodelist[0]
nodelist.pop(0)
if node.left:
nodelist.append(node.left)
if node.right:
nodelist.append(node.right)
sz -= 1
ans += 1
return ans
def maxDepthV1(self, root: TreeNode) -> int:
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res = []
queue = [root]
while len(queue):
len_last_level = len(queue)
tmp_res = []
while len_last_level > 0:
node = queue[0]
queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
tmp_res.append(node.val)
len_last_level -= 1
res.append(tmp_res)
return res[::-1]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
left_depth = self.minDepth(root.left)
right_depth = self.minDepth(root.right)
if not root.left or not root.right:
return left_depth + right_depth + 1
else:
return min(left_depth, right_depth) + 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return sum == root.val
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
res = [[1]]
for level in range(1, numRows):
tmp_res = [1] * (len(res[-1]) + 1)
for num_index in range(1, len(res[-1])):
tmp_res[num_index] = res[-1][num_index - 1] + res[-1][num_index]
res.append(tmp_res)
return res
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
res = [[1]]
for level in range(1, rowIndex+1):
tmp_res = [1] * (len(res[-1]) + 1)
for num_index in range(1, len(res[-1])):
tmp_res[num_index] = res[-1][num_index - 1] + res[-1][num_index]
res.append(tmp_res)
return res[-1]
class Solution:
def maxProfit(self, prices: List[int]) -> int:
minPrice = float('inf')
maxProfit = 0
for price in prices:
maxProfit = max(maxProfit, price - minPrice)
minPrice = min(minPrice, price)
return maxProfit
public:
void rotate(vector& nums, int k) {
if(nums.size() == 0 || k % nums.size() == 0)
return;
int move = k % nums.size();
if(move == 0)
return;
int current, start, prev, next, count = 0, tmp;
for(start = 0; count < nums.size(); start++)
{
current = start;
prev = nums[start];
do{
next = (current + move) % nums.size();
tmp = nums[next];
nums[next] = prev;
prev = tmp;
current = next;
count++;
}while(start != current);
}
return;
}
};
class Solution {
public:
int rob(vector& nums) {
if(nums.size() == 0) return 0;
if(nums.size() == 1) return nums[0];
if(nums.size() == 2) return max(nums[0], nums[1]);
// vector dp;
// dp.push_back(nums[0]);
// dp.push_back(max(nums[0], nums[1]));
// for(int i = 2; i < nums.size(); i++)
// {
// dp.push_back(max(dp[i - 2] + nums[i], dp[i - 1]));
// }
// return dp.back();
int p1 = nums[0];
int p2 = max(nums[0], nums[1]);
int tmp;
for(int i = 2; i < nums.size(); i++)
{
tmp = p2;
p2 = max(p1 + nums[i], p2);
p1 = tmp;
}
return p2;
}
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n)
{
n = n & (n - 1);
count += 1;
}
return count;
}
};
#include
class Solution {
public:
bool isHappy(int n) {
unordered_map map;
while(true){
int next = get_next(n);
if(next == 1){
return true;
}
if(map.size() > 0 && map.find(next) != map.end()){
return false;
}
map.insert({
{next, 0}});
n = next;
}
}
int get_next(int n){
int tmp_sum = 0;
while(n){
int last_digit = n % 10;
tmp_sum += last_digit * last_digit;
n = n / 10;
}
return tmp_sum;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* p = new ListNode(0);
ListNode* q = p;
p->next = head;
while(p && p->next){
if(p->next->val == val){
p->next = p->next->next;
}
else{
p = p->next;
}
}
return q->next;
}
};
#include
class Solution {
public:
int countPrimes(int n) {
if(n <= 2){
return 0;
}
vector isPrime(n, true);
isPrime[0] = false;
isPrime[1] = false;
for(int i = 0; i < sqrt(n); i++)
{
if(isPrime[i] == true){
for(int j = i; i * j < n; j++){
isPrime[i * j] = false;
}
}
}
int count = 0;
for(vector::iterator it = isPrime.begin(); it != isPrime.end(); it++){
if(*it == true){
count += 1;
}
}
return count;
}
};
#include
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.length() == 0 && t.length() == 0){
return true;
}
if(s.length() != t.length()){
return false;
}
unordered_map map_s_t, map_t_s;
for(int i = 0; i < s.length(); i++){
if(map_s_t.find(s[i]) == map_s_t.end()){
// not found
map_s_t[s[i]] = t[i];
}
else if(map_s_t[s[i]] != t[i]){
return false;
}
if(map_t_s.find(t[i]) == map_t_s.end()){
// not found
map_t_s[t[i]] = s[i];
}
else if(map_t_s[t[i]] != s[i]){
return false;
}
}
return true;
}
};
class Solution {
public:
bool isIsomorphic(string s, string t) {
int count_s[256], count_t[256];
for(int i = 0; i < 256; i++){
count_s[i] = count_t[i] = -1;
}
for(int i = 0; i < s.length(); i++){
int int_chr_s = (int)s[i];
int int_chr_t = (int)t[i];
if(count_s[int_chr_s] == -1){
// not init
count_s[int_chr_s] = int_chr_t;
}
else if(count_s[int_chr_s] != int_chr_t){
return false;
}
if(count_t[int_chr_t] == -1){
// not init
count_t[int_chr_t] = int_chr_s;
}
else if(count_t[int_chr_t] != int_chr_s){
return false;
}
}
return true;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* next;
while(cur){
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
// 递归法
if(head == NULL || head->next == NULL)
return head;
ListNode* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
class Solution {
public:
bool containsDuplicate(vector& nums) {
if(nums.size() == 0) return false;
sort(nums.begin(), nums.end());
// for(int i = 0; i < nums.size()-1; i++)
// {
// if(nums[i] == nums[i+1]){
// return true;
// }
// }
for(vector::iterator it = nums.begin(); it < nums.end() - 1; it++){
if(*it == *(it+1)) return true;
}
return false;
}
};
//哈希
unordered_map map;
for(int i = 0; i < nums.size(); i++){
if(map.find(nums[i]) != map.end()){
return true;
}
map[nums[i]] = 1;
}
return false;
#include
class Solution {
public:
bool containsNearbyDuplicate(vector& nums, int k) {
//哈希法
unordered_map map;
for(int i = 0; i < nums.size(); i++){
if(map.find(nums[i]) != map.end()){
if(map[nums[i]] + k >= i){
return true;
}
}
map[nums[i]] = i;
}
return false;
}
};
#include
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
queue s1, s2;
/** Push element x onto stack. */
void push(int x) {
if(s1.empty()){
s2.push(x);
}
else{
s1.push(x);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if(s1.empty()){
if(s2.size() == 0){
return 0; // 异常情况
}
else{
while(s2.size() > 1){
int top = s2.front();
s1.push(top);
s2.pop();
}
int res = s2.front();
s2.pop();
return res;
}
}
else{
while(s1.size() > 1){
int top = s1.front();
s2.push(top);
s1.pop();
}
int res = s1.front();
s1.pop();
return res;
}
}
/** Get the top element. */
int top() {
int res = this->pop();
this->push(res);
return res;
}
/** Returns whether the stack is empty. */
bool empty() {
return s1.empty() && s2.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
#include
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
queue q;
/** Push element x onto stack. */
void push(int x) {
q.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = q.size();
if(size == 0) return 0; //异常情况
while(size > 1){
int val = q.front();
q.pop();
q.push(val);
size--;
}
int res = q.front();
q.pop();
return res;
}
/** Get the top element. */
int top() {
int res = this->pop();
this->push(res);
return res;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL || (root->left == NULL && root->right == NULL)){
return root;
}
TreeNode* inversed_left = invertTree(root->left);
TreeNode* inversed_right = invertTree(root->right);
root->left = inversed_right;
root->right = inversed_left;
return root;
}
};
TreeNode* invertTree(TreeNode* root){
if(!root) return root;
queue q;
q.push(root);
while(!q.empty()){
TreeNode* cur = q.front();
q.pop();
TreeNode* tmp = cur->left;
cur->left = cur->right;
cur->right = tmp;
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
return root;
}
class Solution {
public:
bool isPowerOfTwo(int n) {
//对2取余,余数一直是0的话,说明是2的幂次方。
if(n <= 0) return false;
while(n > 1){
int tmp = n % 2;
if(tmp == 1) return false;
n = n / 2;
}
return true;
}
};
bool isPowerOfTwo(int n) {
if(n <= 0) return 0;
return (n & (n - 1)) == 0;
}
#include
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
stack s1, s2;
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(s1.empty()){
return 0; //异常
}
else{
while(!s1.empty()){
int tmp = s1.top();
s2.push(tmp);
s1.pop();
}
int res = s2.top();
s2.pop();
while(!s2.empty())
{
int tmp = s2.top();
s1.push(tmp);
s2.pop();
}
return res;
}
}
/** Get the front element. */
int peek() {
if(s1.empty()){
return 0; //异常
}
else{
while(!s1.empty()){
int tmp = s1.top();
s2.push(tmp);
s1.pop();
}
int res = s2.top();
while(!s2.empty())
{
int tmp = s2.top();
s1.push(tmp);
s2.pop();
}
return res;
}
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
#include
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
stack s1, s2;
int front = 0;
/** Push element x to the back of queue. */
void push(int x) {
if(s1.empty()) front = x;
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(s1.empty()){
return 0; //异常
}
else{
while(!s1.empty()){
int tmp = s1.top();
s2.push(tmp);
s1.pop();
}
int res = s2.top();
s2.pop();
if(s2.empty()){
front = 0;
}
else{
front = s2.top();
}
while(!s2.empty())
{
int tmp = s2.top();
s1.push(tmp);
s2.pop();
}
return res;
}
}
/** Get the front element. */
int peek() {
return front;
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
//1.快慢指针找到链表中点
ListNode *p1, *p2;
p1 = p2 = head;
while(p2 && p2->next){
p1 = p1->next;
p2 = p2->next->next;
}
//p1是链表的中点
//2.翻转后半部分链表
ListNode* p = inverseLinkList(p1);
while(head && p){
if(head->val != p->val){
return false;
}
head = head->next;
p = p->next;
}
return true;
}
ListNode* inverseLinkList(ListNode* head){
if(!head || !head->next) return head;
ListNode* p = inverseLinkList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
//循环法
ListNode* pre = NULL;
while(p1){
ListNode* tmp = p1->next;
p1->next = pre;
pre = p1;
p1 = tmp;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return root;
if(p->val < root->val && q->val < root->val){
return lowestCommonAncestor(root->left, p, q);
}
else if(p->val > root->val && q->val > root->val){
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return root;
while(true)
{
if(p->val < root->val && q->val < root->val){
root = root->left;
}
else if(p->val > root->val && q->val > root->val){
root = root->right;
}
else{
return root;
}
}
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
ListNode* p = node->next;
node->next = node->next->next;
delete p;
}
};
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length() != t.length())
return false;
int count[26];
for(int i = 0; i < 26; i++) count[i] = 0;
char base = 'a';
int int_base = (int)base;
for(int i = 0; i < s.length(); i++){
count[(int)s[i] - int_base]++;
}
for(int i = 0; i < t.length(); i++){
int pos = (int)t[i] - int_base;
if(count[pos] == 0){
return false;
}
count[pos]--;
}
return true;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector binaryTreePaths(TreeNode* root) {
vector res;
if(root == NULL){
res.push_back("");
return res;
}
if(root->left == NULL && root->right == NULL){
res.push_back(to_string(root->val));
}
if(root->left){
vector left_res = binaryTreePaths(root->left);
for(int i = 0; i < left_res.size(); i++){
res.push_back(to_string(root->val) + "->" + left_res[i]);
}
}
if(root->right){
vector right_res = binaryTreePaths(root->right);
for(int i = 0; i < right_res.size(); i++){
res.push_back(to_string(root->val) + "->" + right_res[i]);
}
}
return res;
}
};
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};
class Solution {
public:
bool isUgly(int num) {
if(num <= 0) return false;
if(num == 1) return true;
if(num % 2 == 0) return isUgly(num / 2);
if(num % 3 == 0) return isUgly(num / 3);
if(num % 5 == 0) return isUgly(num / 5);
return false;
}
};
class Solution {
public:
int missingNumber(vector& nums) {
int n = nums.size();
int target = (0 + n) * (n + 1) / 2;
int sum = 0;
for(int i = 0; i < n; i++){
sum += nums[i];
}
return target - sum;
}
};
class Solution {
public:
int maxProfit(vector& prices) {
if(prices.size() == 0) return 0;
int n = prices.size();
vector> dp;
vector tmp_dp;
tmp_dp.push_back(0);
tmp_dp.push_back(-prices[0]);
dp.push_back(tmp_dp);
for(int i = 1; i < prices.size(); i++){
tmp_dp[0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
tmp_dp[1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp.push_back(tmp_dp);
}
return dp[n - 1][0];
}
// int maxProfit(vector& prices) {
// int max_profit = 0;
// for(int i = 1; i < prices.size(); i++){
// if(prices[i] > prices[i - 1]){
// max_profit += prices[i] - prices[i - 1];
// }
// }
// return max_profit;
// }
};
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int left = 1, right = n;
while(left < right){
int mid = left + (right - left) / 2;
if(isBadVersion(mid) == false){
left = mid + 1;
}
else{
right = mid;
}
}
return left;
}
};
class Solution {
public:
void moveZeroes(vector& nums) {
int cnt = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] != 0){
nums[cnt] = nums[i];
cnt++;
}
}
for(int i = cnt; i < nums.size(); i++)
{
nums[i] = 0;
}
}
};
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector arr;
int start = 0;
for(int i = 0; i < str.size(); i++){
if(i == str.size() - 1){
arr.push_back(str.substr(start, i - start + 1));
}
else if(str[i] == ' ' ){
arr.push_back(str.substr(start, i - start));
start = i + 1;
}
}
map map_c2s;
map map_s2c;
if(pattern.size() != arr.size()) return false;
for(int i = 0; i < pattern.size(); i++){
if(map_c2s.find(pattern[i]) == map_c2s.end())
{
map_c2s[pattern[i]] = arr[i];
}
else{
if(map_c2s[pattern[i]] != arr[i]){
return false;
}
}
if(map_s2c.find(arr[i]) == map_s2c.end())
{
map_s2c[arr[i]] = pattern[i];
}
else{
if(map_s2c[arr[i]] != pattern[i]){
return false;
}
}
}
return true;
}
};
class Solution {
public:
bool canWinNim(int n) {
return n % 4 == 0? false: true;
}
};
#include
class Solution {
public:
string getHint(string secret, string guess) {
int size_s = secret.size(), size_g = guess.size();
if(size_s > size_g){
for(int i = 0; i < size_s - size_g; i++){
secret = '0' + secret;
}
}
else if(size_s < size_g){
for(int i = 0; i < size_g - size_s; i++){
guess = '0' + guess;
}
}
int cntA = 0, cntB = 0;
map map_s, map_g;
for(int i = 0; i < secret.size(); i++){
if(secret[i] == guess[i]){
cntA++;
}
else{
if(map_s.find(secret[i]) == map_s.end()){
map_s[secret[i]] = 1;
}
else{
map_s[secret[i]]++;
}
if(map_g.find(guess[i]) == map_g.end()){
map_g[guess[i]] = 1;
}
else{
map_g[guess[i]]++;
}
}
}
for(map::iterator it = map_s.begin(); it != map_s.end(); it++){
if(map_g.find(it->first) != map_g.end()){
cntB += min(map_g[it->first], map_s[it->first]);
}
}
string res = to_string(cntA) + "A" + to_string(cntB) + "B";
return res;
}
};
class NumArray {
public:
vector arr_sum;
NumArray(vector& nums) {
arr_sum.clear();
arr_sum.push_back(0);
for(int num: nums){
arr_sum.push_back(arr_sum[arr_sum.size() - 1] + num);
}
}
int sumRange(int i, int j) {
if(arr_sum.empty() || i > arr_sum.size() || j > arr_sum.size()) return 0;
return arr_sum[j + 1] - arr_sum[i];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
class Solution {
public:
bool isPowerOfThree(int n) {
int tmp = 0;
while(pow(3, tmp) < n){
tmp++;
}
return pow(3, tmp) == n? true: false;
}
};
class Solution {
public:
bool isPowerOfFour(int num) {
if(num <= 0) return false;
double log_res = log10(num) / log10(4);
return abs(log_res - (int) log_res) == 0? true: false;
}
};
class Solution {
public:
void reverseString(vector& s) {
char tmp;
for(int i = 0; i < s.size() / 2; i++){
tmp = s[i];
s[i] = s[s.size() - 1 - i];
s[s.size() - 1 - i] = tmp;
}
}
};
class Solution {
public:
string reverseVowels(string s) {
vector arr;
arr.push_back('a');
arr.push_back('e');
arr.push_back('i');
arr.push_back('o');
arr.push_back('u');
arr.push_back('A');
arr.push_back('E');
arr.push_back('I');
arr.push_back('O');
arr.push_back('U');
char tmp;
int p = 0, q = s.size() - 1;
while(p < q){
while(p < q && std::find(arr.begin(), arr.end(), s[p]) == arr.end()) p++;
while(q > p && std::find(arr.begin(), arr.end(), s[q]) == arr.end()) q--;
if(p < q){
tmp = s[p];
s[p] = s[q];
s[q] = tmp;
p++;
q--;
}
else{
break;
}
}
return s;
}
};
class Solution {
public:
string reverseVowels(string s) {
string dict_char = "aeiouAEIOU";
char tmp;
int p = 0, q = s.size() - 1;
while(p < q){
while(p < q && dict_char.find(s[p]) == dict_char.npos) p++;
while(q > p && dict_char.find(s[q]) == dict_char.npos) q--;
if(p < q){
tmp = s[p];
s[p] = s[q];
s[q] = tmp;
p++;
q--;
}
else{
break;
}
}
return s;
}
};
class Solution {
public:
bool isPerfectSquare(int num) {
long tmp = 1;
while(true){
if(tmp * tmp >= num) break;
tmp++;
}
return tmp * tmp == num? true: false;
}
};
#include
class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
unordered_map map_1, map_2;
for(int i = 0; i < nums1.size(); i++){
if(map_1.find(nums1[i]) == map_1.end()){
map_1[nums1[i]] = 1;
}
}
vector res;
for(int i = 0; i < nums2.size(); i++){
if(map_1.find(nums2[i]) != map_1.end() && map_2.find(nums2[i]) == map_2.end()){
res.push_back(nums2[i]);
map_2[nums2[i]] = 1;
}
}
return res;
}
};
#include
class Solution {
public:
vector intersection(vector& nums1, vector& nums2) {
unordered_map map_1;
for(int i = 0; i < nums1.size(); i++){
if(map_1.find(nums1[i]) == map_1.end()){
map_1[nums1[i]] = 1;
}
}
vector res;
for(int i = 0; i < nums2.size(); i++){
if(map_1.find(nums2[i]) != map_1.end() && map_1[nums2[i]] == 1){
res.push_back(nums2[i]);
map_1[nums2[i]] = 2;
}
}
return res;
}
};
class Solution {
public:
vector intersect(vector& nums1, vector& nums2) {
unordered_map map_1;
for(int i = 0; i < nums1.size(); i++){
if(map_1.find(nums1[i]) == map_1.end()){
map_1[nums1[i]] = 1;
}
else{
map_1[nums1[i]]++;
}
}
vector res;
for(int i = 0; i < nums2.size(); i++){
if(map_1.find(nums2[i]) != map_1.end() && map_1[nums2[i]] > 0){
res.push_back(nums2[i]);
map_1[nums2[i]]--;
}
}
return res;
}
};
class Solution {
public:
int getSum(int a, int b) {
int res_sum = a, carry = b;
while(carry != 0){
int tmp = res_sum ^ carry;
carry = (unsigned int)(res_sum & carry) << 1;
res_sum = tmp;
}
return res_sum;
}
};
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/
class Solution {
public:
int guessNumber(int n) {
int left = 1, right = n;
while(left < right){
int mid = left + (right - left) / 2;
int guess_res = guess(mid);
if(guess_res == 0){
return mid;
}
else if(guess_res == 1){
left = mid + 1;
}
else{
right = mid - 1;
}
}
return left;
}
};
#include
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map ransom_map;
for(int i = 0; i < ransomNote.size(); i++){
if(ransom_map.find(ransomNote[i]) == ransom_map.end()){
ransom_map[ransomNote[i]] = 1;
}
else{
ransom_map[ransomNote[i]]++;
}
}
for(int i = 0; i < magazine.size(); i++){
char cur = magazine[i];
if(ransom_map.find(cur) != ransom_map.end() and ransom_map[cur] > 0){
ransom_map[cur]--;
}
}
for(unordered_map::iterator it = ransom_map.begin(); it != ransom_map.end(); it++){
if(it->second > 0) return false;
}
return true;
}
};
#include
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int cnt[26];
for(int i = 0; i < 26; i++) cnt[i] = 0;
for(int i = 0; i < ransomNote.size(); i++){
cnt[ransomNote[i] - 'a']++;
}
for(int i = 0; i < magazine.size(); i++){
char cur = magazine[i];
if(cnt[cur - 'a'] > 0){
cnt[cur - 'a']--;
}
}
for(int i = 0; i < 26; i++){
if(cnt[i] > 0) return false;
}
return true;
}
};
class Solution {
public:
int firstUniqChar(string s) {
int cnt[26];
for(int i = 0; i < 26; i++){
cnt[i] = 0;
}
for(char c: s){
cnt[c - 'a']++;
}
for(int i = 0; i < s.size(); i++){
if(cnt[s[i] - 'a'] == 1) return i;
}
return -1;
}
};
class Solution {
public:
char findTheDifference(string s, string t) {
int cnt[26];
for(int i = 0; i < 26; i++){
cnt[i] = 0;
}
for(char c: s){
cnt[c - 'a']++;
}
for(char c: t){
cnt[c - 'a']--;
}
for(int i = 0; i < 26; i++){
if(cnt[i] == -1) return (char)('a' + i);
}
return '0';
}
};
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.size() > t.size()) return false;
int p = 0, q = 0;
while(p < s.size() && q < t.size()){
if(s[p] == t[q]){
p++;
}
q++;
}
return p == s.size();
}
};
class Solution {
public:
bool isSubsequence(string s, string t) {
//动态规划法
int m = t.size();
vector> f(m + 1, vector(26, 0));
for(int i = m; i >= 0; i--){
for(int j = 0; j < 26; j++){
if(i == m){
f[i][j] = m;
}
else if(t[i] == j + 'a'){
f[i][j] = i;
}
else{
f[i][j] = f[i+1][j];
}
}
}
int add = 0;
for(int i = 0; i < s.size(); i++){
if(f[add][s[i] - 'a'] == m) return false;
add = f[add][s[i] - 'a'] + 1;
}
return true;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
queue q;
q.push(root);
int res = 0;
while(q.size() > 0){
TreeNode* node = q.front();
q.pop();
if(node->left){
if(node->left->left == NULL && node->left->right == NULL)
res += node->left->val;
q.push(node->left);
}
if(node->right){
q.push(node->right);
}
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
int res = 0;
if(root->left){
if(root->left->left == NULL && root->left->right == NULL)
res += root->left->val;
res += sumOfLeftLeaves(root->left);
}
if(root->right){
res += sumOfLeftLeaves(root->right);
}
return res;
}
};
class Solution {
public:
string toHex(int num) {
if(num == 0) return string(1, '0');
string res = "";
int tmp;
unsigned int num1 = num;
while(num1){
tmp = num1 % 16;
if(tmp < 10){
res = string(1, '0' + tmp) + res;
}
else{
res = string(1, 'a' + tmp - 10) + res;
}
num1 /= 16;
}
return res;
}
};
class Solution {
public:
int longestPalindrome(string s) {
int cnt[128];
for(int i = 0; i < 128; i++){
cnt[i] = 0;
}
for(char c: s){
cnt[c]++;
}
int odd_cnt = 0;
for(int i = 0; i < 128; i++){
odd_cnt += cnt[i] % 2;
}
return odd_cnt == 0? s.length(): s.length() - odd_cnt + 1;
}
};
class Solution {
public:
vector fizzBuzz(int n) {
vector res;
string tmp;
for(int i = 1; i <= n; i++){
tmp = "";
if(i % 3 != 0 && i % 5 != 0)
{
tmp = to_string(i);
res.push_back(tmp);
continue;
}
if(i % 3 == 0){
tmp += "Fizz";
}
if(i % 5 == 0){
tmp += "Buzz";
}
res.push_back(tmp);
}
return res;
}
};
class Solution {
public:
int thirdMax(vector& nums) {
if(nums.size() == 0) return 0;
vector three_max_num;
for(int num: nums){
if(find(three_max_num.begin(), three_max_num.end(), num) != three_max_num.end()){
continue;
}
if(three_max_num.size() < 3){
three_max_num.push_back(num);
}
else if(num > three_max_num.back()){
three_max_num[2] = num;
}
my_sort(three_max_num);
}
return three_max_num[three_max_num.size() == 3 && nums.size() > 2? 2:0];
}
void my_sort(vector& arr){
// 对三个数字组成的数组进行降序排序
for(int i = 0; i < arr.size(); i++){
for(int j = i + 1; j < arr.size(); j++){
if(arr[i] < arr[j]){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
};
class Solution {
public:
string addStrings(string num1, string num2) {
string res = "";
int add2next = 0, res_add;
int p1 = num1.size() - 1, p2 = num2.size() - 1;
while(p1 >= 0 && p2 >= 0){
res_add = (num1[p1] - '0') + (num2[p2] - '0') + add2next;
add2next = res_add / 10;
res_add = res_add % 10;
res = to_string(res_add) + res;
p1--;
p2--;
}
while(p1 >= 0){
res_add = (num1[p1] - '0') + add2next;
add2next = res_add / 10;
res_add = res_add % 10;
res = to_string(res_add) + res;
p1--;
}
while(p2 >= 0){
res_add = (num2[p2] - '0') + add2next;
add2next = res_add / 10;
res_add = res_add % 10;
res = to_string(res_add) + res;
p2--;
}
if(add2next == 1){
res = "1" + res;
}
return res;
}
};
class Solution {
public:
int countSegments(string s) {
int res_cnt = 0;
bool new_str = false;
for(char c: s){
if(c == ' '){
if(new_str){
res_cnt++;
new_str = false;
}
}
else{
new_str = true;
}
}
return new_str? res_cnt + 1: res_cnt;
}
};
class Solution {
public:
int arrangeCoins(int n) {
int left = 0, right = n;
while(left <= right){
long int mid = left + (right - left) / 2;
long int res_mid = (mid + 1) * mid / 2;
long int res_mid_next = (mid + 1) * (mid + 2) / 2;
if(res_mid == n){
return mid;
}
else if(res_mid > n){
right = mid - 1;
}
else if(res_mid_next > n){
return mid;
}
else{
left = mid + 1;
}
}
return left;
}
};
class Solution {
public:
int compress(vector& chars) {
char tmp_char;
int cnt = 0, pos = 0;
for(int i = 0; i < chars.size(); i++){
if(cnt == 0){
tmp_char = chars[i];
cnt++;
}
else if(tmp_char == chars[i]){
cnt++;
}
else{
chars[pos++] = tmp_char;
if(cnt > 1){
pos = add_num(chars, cnt, pos);
}
tmp_char = chars[i];
cnt = 1;
}
}
if(cnt > 0){
chars[pos++] = tmp_char;
if(cnt > 1)
{
pos = add_num(chars, cnt, pos);
}
}
return pos;
}
int add_num(vector& chars, int cnt, int pos){
int start_pos = pos;
while(cnt){
int res_mod = cnt % 10;
chars[pos++] = res_mod + '0';
cnt /= 10;
}
int end_pos = pos - 1;
while(start_pos < end_pos){
char tmp_exchange = chars[start_pos];
chars[start_pos] = chars[end_pos];
chars[end_pos] = tmp_exchange;
start_pos++;
end_pos--;
}
return pos;
}
};
#include
class Solution {
public:
int numberOfBoomerangs(vector>& points) {
int res = 0;
for(int i = 0; i < points.size(); i++){
unordered_map map;
for(int j = 0; j < points.size(); j++){
if(j == i) continue;
int dist = pow(points[i][0] - points[j][0], 2) + pow(points[i][1] - points[j][1], 2);
if(map.find(dist) == map.end()){
map[dist] = 1;
}
else{
map[dist]++;
}
}
for(unordered_map::iterator it = map.begin(); it != map.end(); it++){
res += it->second * (it->second - 1);
}
}
return res;
}
};
class Solution {
public:
vector findDisappearedNumbers(vector& nums) {
vector res;
for(int i = 0; i < nums.size(); i++){
if(nums[abs(nums[i]) - 1] > 0){
nums[abs(nums[i]) - 1] *= -1;
}
}
for(int i = 0; i < nums.size(); i++){
if(nums[i] > 0){
res.push_back(i + 1);
}
}
return res;
}
};
#include
class Solution {
public:
int minMoves(vector& nums) {
if(nums.size() == 0) return 0;
int moves = 0, min_num = nums[0];
for(auto num: nums){
min_num = min(min_num, num);
}
for(auto num: nums){
moves += num - min_num;
}
return moves;
}
};
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
int count = 0;
int last;
while(count < 32)
{
last = n % 2;
res = res * 2 + last;
n = n / 2;
count += 1;
}
return res;
}
};
#include
class Solution {
public:
int findContentChildren(vector& g, vector& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int cnt = 0, p = 0, q = 0;
while(p < g.size() && q < s.size()){
if(s[q] >= g[p]){
cnt++;
p++;
q++;
}
else{
q++;
}
}
return cnt;
}
};
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int n = s.length();
for(int i = 1; i <= n / 2 ; i++){
if(n % i == 0){
bool match = true;
for(int j = i; j < n; j++){
if(s[j] != s[j - i]) {
match = false;
break;
}
}
if(match) return true;
}
}
return false;
}
};
class Solution {
public:
int hammingDistance(int x, int y) {
int res = x ^ y, cnt = 0;
while(res){
cnt++;
res = res & (res - 1);
}
return cnt;
}
};
class Solution {
public:
int islandPerimeter(vector>& grid) {
int perimeter = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[i].size(); j++){
if(grid[i][j] == 0) continue;
int tmp = 4;
if(j >= 1 && grid[i][j - 1] == 1) tmp--;
if(i >= 1 && grid[i - 1][j] == 1) tmp--;
if(j < grid[i].size() - 1 && grid[i][j + 1] == 1) tmp--;
if(i < grid.size() - 1 && grid[i+1][j] == 1) tmp--;
perimeter += tmp;
}
}
return perimeter;
}
};
class Solution {
public:
int islandPerimeter(vector>& grid) {
int perimeter = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[i].size(); j++){
if(grid[i][j] == 0) continue;
if(i == 0 || grid[i - 1][j] == 0) perimeter += 2;
if(j == 0 || grid[i][j - 1] == 0) perimeter += 2;
}
}
return perimeter;
}
};
#include
class Solution {
public:
int findRadius(vector& houses, vector& heaters) {
int radius = 0;
sort(heaters.begin(), heaters.end());
for(int i = 0; i < houses.size(); i++){
int left = 0, right = heaters.size() - 1, min_dist;
bool found = false;
while(left <= right){
int mid = left + ((right - left) >> 1);
if(heaters[mid] == houses[i]){
found = true;
break;
}
else if(heaters[mid] < houses[i]){
left = mid + 1;
}
else{
right = mid - 1;
}
}
if(found){
min_dist = 0;
}
else{
if(left == 0){
min_dist = abs(heaters[0] - houses[i]);
}
else if(left == heaters.size()){
min_dist = abs(heaters[heaters.size() - 1] - houses[i]);
}
else{
min_dist = min(abs(heaters[left] - houses[i]), abs(heaters[left - 1] - houses[i]));
}
}
radius = max(radius, min_dist);
}
return radius;
}
};
class Solution {
public:
int findComplement(int num) {
int res = 0, mul = 1;
while(num){
int tmp = num % 2;
res += (1 - tmp) * mul;
num = num / 2;
mul = mul << 1;
}
return res;
}
};
class Solution {
public:
string licenseKeyFormatting(string S, int K) {
string res = "";
int cnt = 0;
for(int i = S.length() - 1; i >= 0; i--){
if(S[i] != '-'){
if(cnt == K){
res += "-";
cnt = 0;
}
res += string(1, (char)toupper(S[i]));
cnt++;
}
}
reverse(res.begin(), res.end());
return res;
}
};
class Solution {
public:
int findMaxConsecutiveOnes(vector& nums) {
int max_len = 0, cnt = 0;
for(int num: nums){
if(num == 1){
cnt++;
}
else{
max_len = max(max_len, cnt);
cnt = 0;
}
}
max_len = max(max_len, cnt);
return max_len;
}
};
class Solution {
public:
vector constructRectangle(int area) {
int L, W;
for(int i = 1; i <= sqrt(area); i++){
if(area % i == 0){
W = i;
L = area / i;
}
}
vector res;
res.push_back(L);
res.push_back(W);
return res;
}
};
作者:LeetCode
链接:https://leetcode-cn.com/problems/next-greater-element-i/solution/xia-yi-ge-geng-da-yuan-su-i-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#include
#include
class Solution {
public:
vector nextGreaterElement(vector& nums1, vector& nums2) {
unordered_map next_big;
stack my_stack;
for(int i = 0; i < nums2.size(); i++){
if(my_stack.empty() || nums2[i] <= my_stack.top()){
my_stack.push(nums2[i]);
}
else{
while(!(my_stack.empty()) && nums2[i] > my_stack.top()){
next_big[my_stack.top()] = nums2[i];
my_stack.pop();
}
my_stack.push(nums2[i]);
}
}
while(!(my_stack.empty())){
next_big[my_stack.top()] = -1;
my_stack.pop();
}
vector res;
for(int i = 0; i < nums1.size(); i++){
res.push_back(next_big[nums1[i]]);
}
return res;
}
};
#include
class Solution {
public:
vector findWords(vector& words) {
unordered_map keyboard_map;
string tmp = "QWERTYUIOP";
for(char c: tmp){
keyboard_map[c] = 0;
}
tmp = "ASDFGHJKL";
for(char c: tmp){
keyboard_map[c] = 1;
}
tmp = "ZXCVBNM";
for(char c: tmp){
keyboard_map[c] = 2;
}
vector res;
for(int i = 0; i < words.size(); i++){
bool match = true;
for(int j = 1; j < words[i].size(); j++){
if(keyboard_map[(char)toupper(words[i][j])] != keyboard_map[(char)toupper(words[i][j - 1])]){
match = false;
break;
}
}
if(match){
res.push_back(words[i]);
}
}
return res;
}
};
class Solution {
public:
string convertToBase7(int num) {
if(num < 0){
return "-" + convertToBase7(num * -1);
}
if(num == 0) return "0";
string res = "";
while(num){
res += to_string(num % 7);
num /= 7;
}
reverse(res.begin(), res.end());
return res;
}
};
class Solution {
public:
static bool my_cmp(const pair a, const pair b){
return a.first > b.first;
}
vector findRelativeRanks(vector& nums) {
vector> nums_pair;
for(int i = 0; i < nums.size(); i++){
nums_pair.push_back({nums[i], i});
}
sort(nums_pair.begin(), nums_pair.end(), my_cmp);
vector res(nums.size());
for(int i = 0; i < nums_pair.size(); i++){
if(i > 2){
res[nums_pair[i].second] = to_string(i + 1);
}
else if(i == 0){
res[nums_pair[i].second] = "Gold Medal";
}
else if(i == 1){
res[nums_pair[i].second] = "Silver Medal";
}
else{
res[nums_pair[i].second] = "Bronze Medal";
}
}
return res;
}
};
class Solution {
public:
bool checkPerfectNumber(int num) {
if(num <= 0) return false;
int sum_res = 0;
for(int i = 1; i < sqrt(num); i++){
if(num % i == 0){
sum_res += i + num / i;
}
}
return sum_res == num * 2;
}
};
class Solution {
public:
// int fib(int N) {
// if(N <= 0) return 0;
// if(N == 1) return 1;
// return fib(N - 1) + fib(N - 2);
// }
int fib(int N){
if(N <= 0) return 0;
if(N == 1) return 1;
int n1 = 0, n2 = 1, tmp;
for(int i = 2; i <= N; i++){
tmp = n1 + n2;
n1 = n2;
n2 = tmp;
}
return n2;
}
};
class Solution {
public:
bool detectCapitalUse(string word) {
if(word.length() <= 1) return true;
if(word[0] != (char)toupper(word[0])){
int i = 1;
while(i < word.size()){
if(word[i] == (char)toupper(word[i])) return false;
i++;
}
}
else{
if((word[1] != (char)toupper(word[1]))){
int i = 2;
while(i < word.size()){
if(word[i] == (char)toupper(word[i])) return false;
i++;
}
}
else{
int i = 2;
while(i < word.size()){
if(word[i] != (char)toupper(word[i])) return false;
i++;
}
}
}
return true;
}
};
class Solution {
public:
int findLUSlength(string a, string b) {
if(a.length() == b.length()){
if(a == b){
return -1;
}
else{
return a.length();
}
}
return max(a.length(), b.length());
}
};
class Solution {
public:
int findPairs(vector& nums, int k) {
sort(nums.begin(), nums.end());
int left = 0, right = 1, cnt = 0;
while(right < nums.size()){
int diff = abs(nums[left] - nums[right]);
if(diff == k){
cnt++;
while(right < nums.size() - 1 && nums[right + 1] == nums[right]){
right++;
}
while(left < right && nums[left + 1] == nums[left]){
left++;
}
left++;
while(right <= left){
right++;
}
}
else if(diff < k){
right++;
}
else{
left++;
if(right <= left){
right++;
}
}
}
return cnt;
}
};
class Solution {
public:
static void my_reverse(string& s, int start, int end){
while(start < end){
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
string reverseStr(string s, int k) {
int i;
for(i = 0; i < s.length() / (2 * k); i++){
my_reverse(s, 2 * k * i, 2 * k * i + k - 1);
}
if(s.length() - 2 * k * i < k){
my_reverse(s, 2 * k * i, s.length() - 1);
}
else{
my_reverse(s, 2 * k * i, 2 * k * i + k - 1);
}
return s;
}
};
class Solution {
public:
bool checkRecord(string s) {
int cnt_A = 0;
for(int i = 0; i < s.length(); i++){
if(s[i] == 'A'){
cnt_A++;
if(cnt_A == 2) return false;
}
else if(i < s.length() - 2 && s[i] == 'L' && s[i + 1] == 'L' && s[i + 2] == 'L'){
return false;
}
}
return true;
}
};
class Solution {
public:
static void my_reverse(string& s, int start, int end){
while(start < end){
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
string reverseWords(string s) {
int start = -1, end;
for(int i = 0; i < s.length(); i++){
if(s[i] == ' '){
if(start == -1){
continue;
}
end = i - 1;
my_reverse(s, start, end);
start = -1;
}
else if(start == -1){
start = i;
}
}
if(start != -1){
my_reverse(s, start, s.length() - 1);
}
return s;
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector _children) {
val = _val;
children = _children;
}
};
*/
#include
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL) return 0;
queue q;
q.push(root);
int level = 0;
while(!(q.empty())){
level++;
int len = q.size();
while(len--){
Node* node = q.front();
q.pop();
for(Node* tmp: node->children){
if(tmp != NULL){
q.push(tmp);
}
}
}
}
return level;
}
};
class Solution {
public:
int arrayPairSum(vector& nums) {
sort(nums.begin(), nums.end());
int res;
for(int i = 0; i < nums.size(); i++){
if(i % 2 == 0){
res += nums[i];
}
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res = 0;
int findTilt(TreeNode* root) {
res = 0;
sumOfNodes(root);
return res;
}
int sumOfNodes(TreeNode* root){
if(root == NULL) return 0;
int left = sumOfNodes(root->left);
int right = sumOfNodes(root->right);
res += abs(left - right);
return left + right + root->val;
}
};
class Solution {
public:
vector> matrixReshape(vector>& nums, int r, int c) {
if(nums.size() == 0) return nums;
if(nums.size() * nums[0].size() != r * c) return nums;
vector> res(r, vector(c));
int row = 0, col = 0;
for(int i = 0; i < nums.size(); i++){
for(int j = 0; j < nums[i].size(); j++){
res[row][col] = nums[i][j];
col++;
if(col == c){
row++;
col = 0;
}
}
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if(t == NULL) return true;
if(s == NULL) return false;
bool root = isSameTree(s, t);
bool left = false, right = false;
if(!root){
left = isSubtree(s->left, t);
if(!left){
right = isSubtree(s->right, t);
if(!right){
return false;
}
}
}
return true;
}
bool isSameTree(TreeNode* s, TreeNode* t){
if(s == NULL && t == NULL) return true;
if(s == NULL || t == NULL) return false;
if(s->val == t->val){
return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
}
return false;
}
};
#include
class Solution {
public:
int distributeCandies(vector& candies) {
unordered_map candy_count;
int total_count = 0, num_type = 0;
for(int i = 0; i < candies.size(); i++){
total_count++;
if(candy_count.find(candies[i]) == candy_count.end()){
candy_count[candies[i]] = 1;
num_type++;
}
}
return min(total_count / 2, num_type);
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector preorder(Node* root) {
vector res;
if(root == NULL) return res;
res.push_back(root->val);
if(!(root->children.empty())){
for(Node* tmp: root->children){
for(int val: preorder(tmp)){
res.push_back(val);
}
}
}
return res;
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector postorder(Node* root) {
vector res;
if(root == NULL) return res;
if(!(root->children.empty())){
for(Node* tmp: root->children){
for(int val: postorder(tmp)){
res.push_back(val);
}
}
}
res.push_back(root->val);
return res;
}
};
#include
class Solution {
public:
int findLHS(vector& nums){
unordered_map my_map;
for(int i = 0; i < nums.size(); i++){
if(my_map.find(nums[i]) != my_map.end()){
my_map[nums[i]]++;
}
else{
my_map[nums[i]] = 1;
}
}
int res = 0;
for(unordered_map::iterator it = my_map.begin(); it != my_map.end(); it++){
int key = it->first;
if(my_map.find(key + 1) != my_map.end()){
res = max(res, my_map[key] + my_map[key + 1]);
}
}
return res;
}
// int findLHS(vector& nums) {
// int res = 0;
// for(int i = 0; i < nums.size(); i++){
// int count = 0;
// bool flag = false;
// for(int j = 0; j < nums.size(); j++){
// if(nums[j] == nums[i]){
// count++;
// }
// else if(nums[j] + 1 == nums[i]){
// count++;
// flag = true;
// }
// }
// if(flag){
// res = max(res, count);
// }
// }
// return res;
// }
};
class Solution {
public:
int maxCount(int m, int n, vector>& ops) {
int min_row = m, min_col = n;
for(int i = 0; i < ops.size(); i++){
min_row = min(min_row, ops[i][0]);
min_col = min(min_col, ops[i][1]);
}
return min_row * min_col;
}
};
#include
class Solution {
public:
vector findRestaurant(vector& list1, vector& list2) {
unordered_map map1, map2;
for(int i = 0; i < list1.size(); i++){
if(map1.find(list1[i]) == map1.end()){
map1[list1[i]] = i;
}
}
for(int i = 0; i < list2.size(); i++){
if(map2.find(list2[i]) == map2.end()){
map2[list2[i]] = i;
}
}
int min_sum = list1.size() + list2.size();
vector res;
for(unordered_map::iterator it = map1.begin(); it != map1.end(); it++){
string str = it->first;
if(map2.find(str) != map2.end()){
int tmp_sum = map1[str] + map2[str];
if(tmp_sum < min_sum){
min_sum = tmp_sum;
res.clear();
res.push_back(str);
}
else if(tmp_sum == min_sum){
res.push_back(str);
}
}
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* t, string& res){
if(t != NULL){
res += to_string(t->val);
if(t->left == NULL && t->right == NULL) return;
res += "(";
dfs(t->left, res);
res += ")";
if(t->right != NULL){
res += "(";
dfs(t->right, res);
res += ")";
}
}
}
string tree2str(TreeNode* t) {
string res;
dfs(t, res);
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 == NULL && t2 == NULL) return t1;
if(t1 != NULL && t2 != NULL){
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
}
return t1 == NULL? t2: t1;
}
};
class Solution {
public:
int maximumProduct(vector& nums) {
if(nums.size() < 3) return 0;
sort(nums.begin(), nums.end());
int mul_last_three = 1;
for(int i = nums.size() - 3; i < nums.size(); i++){
mul_last_three *= nums[i];
}
if(nums[0] >= 0 || nums[nums.size() - 1] < 0){
return mul_last_three;
}
else if(nums[1] < 0){
int res = max(mul_last_three, nums[0] * nums[1] * nums[nums.size() - 1]);
return res;
}
return mul_last_three;
}
};
class Solution {
public:
bool judgeSquareSum(int c) {
for(int a = 0; a <= sqrt(c); a++){
int b = sqrt(c - a * a);
if(a * a + b * b == c) return true;
}
return false;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include
class Solution {
public:
vector averageOfLevels(TreeNode* root) {
vector res;
if(root == NULL) return res;
queue q;
q.push(root);
while(q.size() > 0){
int size = q.size();
int size_copy = size;
double sum = 0;
while(size--){
TreeNode* node = q.front();
q.pop();
sum += node->val;
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
res.push_back(sum / size_copy);
}
return res;
}
};
class Solution {
public:
double findMaxAverage(vector& nums, int k) {
if(k <= 0) return 0.0;
if(nums.size() < k) return 0.0;
int sum = 0, max_sum;
for(int i = 0; i < nums.size(); i++){
if(i < k){
sum += nums[i];
if(i == k - 1){
max_sum = sum;
}
}
else{
sum = sum - nums[i - k] + nums[i];
max_sum = max(max_sum, sum);
}
}
return (double) max_sum / k;
}
};
class Solution {
public:
vector findErrorNums(vector& nums) {
vector res;
if(nums.size() == 0) return res;
sort(nums.begin(), nums.end());
int sum = 0, repeat_num = 0;
bool found = false;
for(int i = 0; i < nums.size(); i++){
sum += nums[i];
if(!found && i > 0 && nums[i] == nums[i - 1]){
repeat_num = nums[i];
found = true;
}
}
res.push_back(repeat_num);
res.push_back((1 + nums.size()) * nums.size() / 2 - (sum - res[0]));
return res;
}
};
class Solution {
public:
vector findErrorNums(vector& nums) {
vector res;
if(nums.size() == 0) return res;
int repeat_num, missing_num;
for(int i = 0; i < nums.size(); i++){
int abs_pos = abs(nums[i]) - 1;
if(nums[abs_pos] < 0){
repeat_num = abs(nums[i]);
}
else{
nums[abs_pos] *= -1;
}
}
for(int i = 0; i < nums.size(); i++){
if(nums[i] > 0){
missing_num = i + 1;
}
}
res.push_back(repeat_num);
res.push_back(missing_num);
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == NULL) return root;
if(root->val < low){
return trimBST(root->right, low, high);
}
if(root->val > high){
return trimBST(root->left, low, high);
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
if(root == NULL){
return -1;
}
int res = -1;
dfs(root, root->val, res);
return res;
}
void dfs(TreeNode* root, int min_val, int& res){
if(root == NULL || (res != -1 && root->val >= res)) return;
if(root->val != min_val){
res = root->val;
}
dfs(root->left, min_val, res);
dfs(root->right, min_val, res);
}
};
class Solution {
public:
int findLengthOfLCIS(vector& nums) {
int res = 0, count = 0;
for(int i = 0; i < nums.size(); i++){
if(i == 0){
count = 1;
}
else{
if(nums[i] > nums[i - 1]){
count++;
}
else{
res = max(res, count);
count = 1;
}
}
}
res = max(res, count);
return res;
}
};
class Solution {
public:
bool validPalindrome(string s) {
bool drop_letter = false;
int p = 0, q = s.size() - 1;
while(p <= q){
if(s[p] == s[q]){
p++;
q--;
}
else{
return isValid(s, p + 1, q) || isValid(s, p, q-1);
}
}
return true;
}
private:
bool isValid(string& s, int p, int q){
while(p <= q){
if(s[p] == s[q]){
p++;
q--;
}
else{
return false;
}
}
return true;
}
};
class Solution {
public:
int calPoints(vector& ops) {
vector scores;
int res = 0;
for(string s: ops){
if(s == "+"){
if(scores.size() < 2) return -1;
scores.push_back(scores[scores.size() - 2] + scores[scores.size() - 1]);
}
else if(s == "D"){
if(scores.size() == 0) return -1;
scores.push_back(scores[scores.size() - 1] * 2);
}
else if(s == "C"){
if(scores.size() == 0) return -1;
scores.pop_back();
}
else{
scores.push_back(stoi(s));
}
}
for(int s: scores){
res += s;
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int res = 0;
longestPath(root, res);
return res;
}
private:
int longestPath(TreeNode* root, int& res){
if(root == NULL) return 0;
int left_length = longestPath(root->left, res);
int right_length = longestPath(root->right, res);
int left_row = 0, right_row = 0;
if(root->left && root->left->val == root->val){
left_row = left_length + 1;
}
if(root->right && root->right->val == root->val){
right_row = right_length + 1;
}
res = max(res, left_row + right_row);
return max(left_row, right_row);
}
};
/*
// Definition for Employee.
class Employee {
public:
int id;
int importance;
vector subordinates;
};
*/
#include
#include
class Solution {
public:
int getImportance(vector employees, int id) {
if(employees.size() == 0) return 0;
queue q;
unordered_map importance_map;
unordered_map> employee_map;
for(int i = 0; i < employees.size(); i++){
importance_map[employees[i]->id] = employees[i]->importance;
employee_map[employees[i]->id] = employees[i]->subordinates;
}
int sum = 0;
if(employee_map.find(id) != employee_map.end()){
q.push(id);
while(q.size() > 0){
int t_id = q.front();
q.pop();
sum += importance_map[t_id];
for(int i = 0; i < employee_map[t_id].size(); i++){
q.push(employee_map[t_id][i]);
}
}
}
return sum;
}
};
class Solution {
public:
bool hasAlternatingBits(int n) {
int last_digit = n % 2;
n /= 2;
int tmp;
while(n != 0){
tmp = n % 2;
if(tmp + last_digit != 1) return 0;
n /= 2;
last_digit = tmp;
}
return true;
}
};
class Solution {
public:
int countBinarySubstrings(string s) {
vector vec_count;
int count = 0;
char cur;
for(int i = 0; i < s.length(); i++){
if(count == 0){
count = 1;
cur = s[i];
}
else{
if(s[i] == cur){
count++;
}
else{
vec_count.push_back(count);
count = 1;
cur = s[i];
}
}
}
vec_count.push_back(count);
int res = 0;
for(int i = 0; i < vec_count.size() - 1; i++){
res += min(vec_count[i], vec_count[i+1]);
}
return res;
}
};