1071. Greatest Common Divisor of Strings

For strings S and T, we say "T divides S" if and only if S = T + ... + T  (T concatenated with itself 1 or more times)

Return the largest string X such that X divides str1 and X divides str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""

Note:

  1. 1 <= str1.length <= 1000
  2. 1 <= str2.length <= 1000
  3. str1[i] and str2[i] are English uppercase letters.

Approach #1: Simulate. [Java]

class Solution {
public String gcdOfStrings(String str1, String str2) {
int len1 = str1.length(), len2 = str2.length();
int minLen = Math.min(str1.length(), str2.length());
while (minLen > 0) {
if (len1 % minLen == 0 && len2 % minLen == 0) {
String subStr = str2.substring(0, minLen);
if (isRepeat(str1, subStr) && isRepeat(str2, subStr)) {
return subStr;
}
}
minLen--;
}
return new String("");
} public boolean isRepeat(String target, String subStr) {
int n = subStr.length();
for (int i = 0; i < target.length(); ++i) {
if (target.charAt(i) != subStr.charAt(i%n))
return false;
}
return true;
}
}

  

Analysis:

The greatest common divisor of string's length must is the divisor of str1.length() and str2.length(). So we can find the min length of str1.length() and str2.length() as the common divisor of string's length at the first. If divisor string's length is the divisor of str1.length and str2.length, and str1, str2 are consituted by repeating divisor string, we return the longest divisor string.

1072. Flip Columns For Maximum Number of Equal Rows

Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column.  Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.

Return the maximum number of rows that have all values equal after some number of flips.

Example 1:

Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.

Example 2:

Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.

Example 3:

Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.

Note:

  1. 1 <= matrix.length <= 300
  2. 1 <= matrix[i].length <= 300
  3. All matrix[i].length's are equal
  4. matrix[i][j] is 0 or 1

Approach #1:

class Solution {
public int maxEqualRowsAfterFlips(int[][] matrix) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < matrix.length; ++i) {
String key = Arrays.toString(matrix[i]);
for (int j = 0; j < matrix[i].length; ++j) matrix[i][j] ^= 1;
String rev = Arrays.toString(matrix[i]);
map.put(key, map.getOrDefault(key, 0) + 1);
map.put(rev, map.getOrDefault(rev, 0) + 1);
}
int ret = -1;
for (String key : map.keySet()) {
ret = Math.max(ret, map.get(key));
} return ret;
}
}

  

Analysis:

Intuitively, if two rows have the same numbers or have reverse numbers(0->1 or 1->0), we can flip some column to make them only contains 0 or 1. So we can use a map, the row number to a string as the key and the count as the value, otherwise, we should reverse the  row's numbers as the key, too.

Finally, find the max value in the map.

1073. Adding Two Negabinary Numbers

Given two numbers arr1 and arr2 in base -2, return the result of adding them together.

Each number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.

Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

Example 1:

Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]
Output: [1,0,0,0,0]
Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.

Note:

  1. 1 <= arr1.length <= 1000
  2. 1 <= arr2.length <= 1000
  3. arr1 and arr2 have no leading zeros
  4. arr1[i] is 0 or 1
  5. arr2[i] is 0 or 1

Approach #1:

class Solution {
public int[] addNegabinary(int[] arr1, int[] arr2) {
int i = arr1.length - 1, j = arr2.length - 1, carry = 0;
Stack<Integer> stack = new Stack<>();
while (i >= 0 || j >= 0 || carry != 0) {
int n1 = i >= 0 ? arr1[i--] : 0;
int n2 = j >= 0 ? arr2[j--] : 0;
carry = n1 + n2 + carry;
stack.push(carry & 1);
carry = -(carry >> 1);
}
while (!stack.empty() && stack.peek() == 0) stack.pop();
int[] ret = new int[stack.size()];
int index = 0;
while (!stack.empty()) {
ret[index++] = stack.pop();
}
return ret.length == 0 ? new int[1] : ret;
}
}

  

Approach #2: [WA]

class Solution {
public int[] addNegabinary(int[] arr1, int[] arr2) {
int num1 = 0, num2 = 0;
int len1 = arr1.length - 1, len2 = arr2.length - 1;
for (int i = 0; i < arr1.length; ++i) {
if (arr1[i] == 1) {
num1 += Math.pow(-2, len1);
len1--;
} else {
len1--;
}
}
for (int i = 0; i < arr2.length; ++i) {
if (arr2[i] == 1) {
num2 += Math.pow(-2, len2);
len2--;
} else {
len2--;
}
}
int sum = num1 + num2;
List<Integer> list = new ArrayList<Integer>();
if (sum == 0) list.add(0);
while (sum != 0) {
int remainder = sum % (-2);
sum = sum / (-2);
// System.out.println(remainder + " " + sum);
if (remainder < 0) {
remainder += 2;
sum += 1;
}
list.add(remainder);
}
Collections.reverse(list); int[] ret = new int[list.size()];
for (int i = 0; i < list.size(); ++i)
ret[i] = list.get(i); return ret;
}
}

  

1074. Number of Submatrices That Sum to Target

Given a matrix, and a target, return the number of non-empty submatrices that sum to target.

A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.

Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.

Example 1:

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.

Example 2:

Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.

Note:

  1. 1 <= matrix.length <= 300
  2. 1 <= matrix[0].length <= 300
  3. -1000 <= matrix[i] <= 1000
  4. -10^8 <= target <= 10^8

Approach #1:

class Solution {
public int numSubmatrixSumTarget(int[][] matrix, int target) {
int row = matrix.length, col = matrix[0].length;
int[][] sumMatrix = new int[row+1][col+1];
sumMatrix[1][1] = matrix[0][0];
for (int i = 2; i <= row; ++i)
sumMatrix[i][1] = matrix[i-1][0] + sumMatrix[i-1][1];
for (int j = 2; j <= col; ++j)
sumMatrix[1][j] = matrix[0][j-1] + sumMatrix[1][j-1];
for (int i = 2; i <= row; ++i) {
for (int j = 2; j <= col; ++j) {
sumMatrix[i][j] = sumMatrix[i][j-1] + sumMatrix[i-1][j] - sumMatrix[i-1][j-1] + matrix[i-1][j-1]; }
} int count = 0;
for (int i = 1; i <= row; i++) {
for (int j = 1; j <= col; ++j) {
count += countTarget(i, j, target, sumMatrix);
}
} return count;
} public int countTarget(int x, int y, int target, int[][] sumMatrix) {
int subCount = 0, sum = 0;
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
sum = sumMatrix[x][y] - sumMatrix[i][y] - sumMatrix[x][j] + sumMatrix[i][j];
if (sum == target) subCount++;
}
}
return subCount;
}
}

  

Analysis:

Firstly, we calculate the sum of a sub-matrix from [0, 0] to [i, j].

Secondly, traveling all the points in the sub-matrix as the start point and claculate the sum, if the sum equal to the target, the count number increase one.

Weekly Contest 139的更多相关文章

  1. LeetCode Weekly Contest 8

    LeetCode Weekly Contest 8 415. Add Strings User Accepted: 765 User Tried: 822 Total Accepted: 789 To ...

  2. Leetcode Weekly Contest 86

    Weekly Contest 86 A:840. 矩阵中的幻方 3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等. 给定一个 ...

  3. leetcode weekly contest 43

    leetcode weekly contest 43 leetcode649. Dota2 Senate leetcode649.Dota2 Senate 思路: 模拟规则round by round ...

  4. LeetCode Weekly Contest 23

    LeetCode Weekly Contest 23 1. Reverse String II Given a string and an integer k, you need to reverse ...

  5. LeetCode之Weekly Contest 91

    第一题:柠檬水找零 问题: 在柠檬水摊上,每一杯柠檬水的售价为 5 美元. 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯. 每位顾客只买一杯柠檬水,然后向你付 5 美元.10  ...

  6. LeetCode Weekly Contest

    链接:https://leetcode.com/contest/leetcode-weekly-contest-33/ A.Longest Harmonious Subsequence 思路:hash ...

  7. LeetCode Weekly Contest 47

    闲着无聊参加了这个比赛,我刚加入战场的时候时间已经过了三分多钟,这个时候已经有20多个大佬做出了4分题,我一脸懵逼地打开第一道题 665. Non-decreasing Array My Submis ...

  8. 75th LeetCode Weekly Contest Champagne Tower

    We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so ...

  9. LeetCode之Weekly Contest 102

    第一题:905. 按奇偶校验排序数组 问题: 给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素. 你可以返回满足此条件的任何数组作为答案. 示例: 输入: ...

随机推荐

  1. Redis缓存中的常见问题

    缓存穿透:是指查询一个Redis和数据库中都不存在的数据. 问题:查询一个Redis和数据库中都不存在的数据,大量请求去访问数据库,导致数据库宕机. 解决办法: 1.根据id查询,如果id是自增的,将 ...

  2. C++中tuple类型

    tuple是C++11新标准里的类型.它是一个类似pair类型的模板.pair类型是每个成员变量各自可以是任意类型,但是只能有俩个成员,而tuple与pair不同的是它可以有任意数量的成员.但是每个确 ...

  3. Kubernetes-2.组件

    内容主要摘自官网文档资料 官网地址 本文概述了交付正常运行的Kubernetes集群所需的各种组件. 本文编写基于kubernetes v1.17版本 目录 Kubernetes集群 Master组件 ...

  4. 基于 react + electron 开发及结合爬虫的应用实践🎅

    前言 Electron 是一个可以使用 Web 技术如 JavaScript.HTML 和 CSS 来创建跨平台原生桌面应用的框架.借助 Electron,我们可以使用纯 JavaScript 来调用 ...

  5. Java练习——抽象类

    需求: 2辆宝马,1辆别克商务舱,1辆金龙(34)座,租5天共多少租金.   轿车 客车(金杯.金龙) 车型 别克商务舱GL8 宝马550i 别克林荫大道 <=16座 >16座 日租费(元 ...

  6. Spring-06 AOP

    Spring-06 AOP AOP 1.简介 AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术. AO ...

  7. HDOJ-1540(线段树+较复杂的单点修改和区间查询)

    Tunnel Warfare HDOJ-1540 这题关于线段树的操作有一定的难度,需要较好的思维能力. 关于题目的详细解答已经在代码中体现了. #include<iostream> #i ...

  8. Web微信协议

    [文档]Web微信协议 1.登录 1.1 获取uuid(get) 请求 https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&red ...

  9. 推荐模型DeepCrossing: 原理介绍与TensorFlow2.0实现

    DeepCrossing是在AutoRec之后,微软完整的将深度学习应用在推荐系统的模型.其应用场景是搜索推荐广告中,解决了特征工程,稀疏向量稠密化,多层神经网路的优化拟合等问题.所使用的特征在论文中 ...

  10. 为 .NET 打 Call,为国产平台 Gitee 打 Call,我的 .NET/C# 开源项目清单,同步维护于 Github 和 Gitee

    所有项目遵循 MIT 开源协议.可以随意使用,但是需在源代码和产品关于画面保留版权声明和我的网站链接,谢谢. Sheng.Winform.IDE Github:https://github.com/i ...