题目编号对应1071-1074
rank:https://leetcode.com/contest/weekly-contest-139/ranking
1071:枚举约数
package com.netease.music.leetcode;
/**
* Created by dezhonger on 2019/6/3
*/
public class Leetcode1071 {
public static void main(String[] args) {
System.out.println(new Leetcode1071().gcdOfStrings("abcabc", "abc"));
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
boolean check(String s1, String s2, int g) {
String s = s1.substring(0, g);
if (check(s, s1) && check(s, s2)) return true;
return false;
}
private boolean check(String s, String s1) {
int g = s.length();
for (int i = 0; i < s1.length(); i += g) {
if (!s.equals(s1.substring(i, i + g))) {
return false;
}
}
return true;
}
public String gcdOfStrings(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int g = gcd(len1, len2);
int res = 0;
for (int i = g; i >= 1; i--) {
if (g % i == 0 && check(str1, str2, i)) {
res = Math.max(res, i);
break;
}
}
if (res == 0) return "";
else return str1.substring(0, res);
}
}
1072:贪心
package com.netease.music.leetcode;
import java.util.Arrays;
/**
* Created by dezhonger on 2019/6/3
*/
public class Leetcode1072 {
public int maxEqualRowsAfterFlips(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int res = 1;
for (int i = 0; i < n; i++) {
int c = 1;
for (int j = i + 1; j < n; j++) {
if (Arrays.equals(matrix[i], matrix[j])) c++;
else {
boolean f = true;
for (int k = 0; k < m; k++) {
if (matrix[i][k] + matrix[j][k] != 1) {
f = false;
break;
}
}
if (f) c++;
}
}
res = Math.max(res, c);
}
return res;
}
}
1073:负数进位制 (似乎和这个有点像https://leetcode.com/problems/convert-to-base-2/)
https://leetcode-cn.com/contest/weekly-contest-130
这个负数进位制的不太会。。
1074:二维矩阵和,枚举两行,然后枚举列
package com.netease.music.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dezhonger on 2019/6/3
*/
public class Leetcode1074 {
public int numSubmatrixSumTarget(int[][] a, int target) {
int n = a.length;
int m = a[0].length;
int[][] cum = new int[n + 1][m + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cum[i + 1][j + 1] = cum[i + 1][j] + cum[i][j + 1] - cum[i][j] + a[i][j];
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
Map map = new HashMap<>();
for (int k = 0; k <= m; k++) {
int v = cum[j + 1][k] - cum[i][k];
if (map.containsKey(v - target)) {
ans += map.get(v - target);
}
if (map.containsKey(v)) {
map.put(v, map.get(v) + 1);
} else {
map.put(v, 1);
}
}
}
}
return ans;
}
}