题目类型:滑动窗口
题目难度:简单
class Solution {
public int minimumDifference(int[] nums, int k) {
if(k == 1) return 0;
Arrays.sort(nums);
int i = 0, j = 0;
int min = 100000;
while(j < nums.length){
if(j - i + 1 > k){
i++;
}
if(j - i + 1 == k){
min = Math.min(min, nums[j] - nums[i]);
}
j++;
}
return min;
}
}
思路分析:
因为子串的长度固定为3,所以只需要截取每个长度为3的子字符串,判断这些子字符串中的字符是否重复,如果重复,就不算,三个都不重复时,才将其加上。
代码:
class Solution {
public int countGoodSubstrings(String s) {
if(s.length() < 3) return 0;
int res = 0;
for(int i = 0; i <= s.length() - 3; i++){
String sub = s.substring(i, i+3);
if(sub.charAt(0) != sub.charAt(1) && sub.charAt(0) != sub.charAt(2) && sub.charAt(2) != sub.charAt(1)){
res++;
}
}
return res;
}
}
aeiou
存入HashMap中,遍历整个字符串,如果当前位与前一位的差值为1或0,这种情况是正常情况,如果start位是a且end位是u,就将其加上;class Solution {
public int longestBeautifulSubstring(String word) {
int n = word.length();
Map<Character, Integer> valueMap = new HashMap();
valueMap.put('a',0);
valueMap.put('e',1);
valueMap.put('i',2);
valueMap.put('o',3);
valueMap.put('u',4);
char[] nums = word.toCharArray();
int start=0,end=0;
int res = 0;
while(end<n-1) {
end++;
if(nums[start] == 'a' && (valueMap.get(nums[end-1])+1 == valueMap.get(nums[end]) ||
valueMap.get(nums[end-1]) == valueMap.get(nums[end]))) {
if(nums[start] == 'a' && nums[end] == 'u') {
res = Math.max(end-start+1, res);
}
} else {
start = end;
}
}
return res;
}
}
题目类型:排序
难度:简单
class Solution {
public boolean isStraight(int[] nums) {
Arrays.sort(nums);
for(int i = 0; i < nums.length - 1; i++){
if(nums[i] == nums[i+1] && nums[i] != 0){
return false;
}
}
int pre = 0;
boolean flag = false;
for(int i = 0; i < nums.length - 1; i++){
if(nums[i] == 0){
pre++;
}else{
if((nums[i+1] - nums[i] == 1) || (nums[i+1] - nums[i] <= pre + 1)){
flag = true;
}else{
return false;
}
}
}
return flag;
}
}
x+y < y+x
那么x小于y;x+y > y+x
那么x大于y;class Solution {
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i = 0; i < nums.length; i++)
strs[i] = String.valueOf(nums[i]);
Arrays.sort(strs, (x, y) -> (x + y).compareTo(y + x));
StringBuilder res = new StringBuilder();
for(String s : strs)
res.append(s);
return res.toString();
}
}