(该模块仅为记录本人的leetcode的练习记录)
1748.唯一元素的和(easy)
解题思路:用一个长度为100的数组记录每个数出现的次数,然后计算出现一次的元素的总和。(原题中有说明数据范围为1-100)
代码:
package LeetCode.Code2022.January;
public class Solution1748 {
public int sumOfUnique(int[] nums) {
int[] countNums = new int[101];
for (int i = 0; i < nums.length; i++) {
countNums[nums[i]]++;
}
int ans = 0;
for (int i = 1; i < 101; i++) {
if (countNums[i] == 1) {
ans += i;
}
}
return ans;
}
}
1763.最长的美好字符串(easy)
解题思路:滑窗+暴力。
代码:
package LeetCode.Code2022.January;
import java.util.Arrays;
public class Solution1763 {
public String longestNiceSubstring(String s) {
int[] upCaseCount = new int[26];
int[] lowCaseCount = new int[26];
String ans = "";
int begin = 0;
while (begin < s.length() - 1) {
int end = begin + 1;
add(upCaseCount, lowCaseCount, s.charAt(begin));
while (end < s.length()) {
add(upCaseCount, lowCaseCount, s.charAt(end));
if (isSimilar(upCaseCount, lowCaseCount)) {
if (end - begin + 1 > ans.length()) {
ans = s.substring(begin, end + 1);
}
}
end++;
}
begin++;
Arrays.fill(upCaseCount, 0);
Arrays.fill(lowCaseCount, 0);
}
return ans;
}
boolean isSimilar(int[] arr1, int[] arr2) {
int len1 = arr1.length;
int len2 = arr2.length;
if (len1 != len2) {
return false;
}
for (int i = 0; i < len1; i++) {
if ((arr1[i] > 0 && arr2[i] > 0)
|| (arr1[i] == 0 && arr2[i] == 0)) {
continue;
} else {
return false;
}
}
return true;
}
void add(int[] upCaseCount, int[] lowCaseCount, char target) {
if (Character.isUpperCase(target)) {
upCaseCount[target - 'A']++;
} else {
lowCaseCount[target - 'a']++;
}
}
}
1816.截断句子(easy)
解题思路:将句子按照空格拆分然后用空格拼接指定个数单词即可
代码:
package LeetCode.Code2022.January;
import java.util.Arrays;
public class Solution1816 {
public String truncateSentence(String s, int k) {
return String.join(" ", Arrays.copyOf(s.split(" "), k));
}
}