简单题过过瘾;突击学习,记忆为主,感觉至上,多看看实现好的数据结构,java方法
1952. 三除数
class Solution {
public boolean isThree(int n) {
int cnt = 0;
for (int i = 2; i < n; i++) {
if ((n % i) == 0) {
System.out.println(i);
cnt++;
}
}
System.out.println(cnt);
return cnt == 1;
}
}
2000. 反转单词前缀
// 2000
public class reversePrefix {
public static void main(String[] args) {
System.out.println(reversePrefix("abcdefd", 'd'));
}
public static String reversePrefix(String word, char ch) {
int i = word.indexOf(ch);
String left = word.substring(0, i + 1);
String right = word.substring(i + 1);
return new StringBuilder(left).reverse().append(right).toString();
}
}
public class countKDifference2006 {
public static void main(String[] args) {
int i = countKDifference(new int[]{3,2,1,5,4}, 2);
System.out.println(i);
}
public static int countKDifference(int[] nums, int k) {
// 最简双指针
int left = 0;
int ans = 0;
int len = nums.length;
while (left < len) {
int right = left + 1;
while (right < len) {
if (Math.abs(nums[left] - nums[right]) == k) {
ans += 1;
}
right++;
}
left++;
}
return ans;
}
}
2011. 执行操作后的变量值
class Solution {
public int finalValueAfterOperations(String[] operations) {
int x =0 ;
for (String operation : operations) {
switch (operation){
case "X++":
++x;
break;
case "++X":
++x;
break;
case"X--":
--x;
break;
case"--X":
--x;
break;
}
}
return x;
}
}
public class minimumMoves2027 {
public static void main(String[] args) {
System.out.println(minimumMoves("OXOX"));
}
public static int minimumMoves(String s) {
int covered = -1, res = 0;
for (int i = 0; i < s.length(); i++) {
// X开头的地方可以覆盖后面的两个字符串,直接跳过
if (s.charAt(i) == 'X' && i > covered) {
res++;
covered = i + 2;
}
}
return res;
}
}
2765. 最长交替子数组
class Solution {
public int alternatingSubarray(int[] nums) {
// 双指针
int left = 0;
int ans = 0;
while (left < nums.length) {
int right = left;
int res = 1;
while (right < nums.length) {
right++;
if (right < nums.length && ((nums[right] - nums[left]) == (res % 2))) {
res++;
}else {
ans = Math.max(res,ans);
break;
}
if(right == (nums.length-1)){
ans = Math.max(res,ans);
}
}
left++;
}
return ans<2?-1:ans;
}
}