🔥 一、字符串翻转
例如:将字符串“45abc,+ed== gf”翻转成为“45cba,+de== fg”
要知道,我们翻转的是字母,但是这个字符串又不是全是字母
问题就是我们怎么得到字母
三角形标注的是->首字母
圆形标注的是 —>尾字母
需要两个变量
package day03;
public class strRever {
public static void main(String[] args) {
String str = "45abc1=45cd";
System.out.println(str);
String s = revstr(str);
System.out.println(s);
}
public static String revstr(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if ( (ch[i] >= 'A' && ch[i] <= 'Z') || ( ch[i] >= 'a' && ch[i] <= 'z')) {
int j = i + 1;
while (j < ch.length && ( ( ch[j] >= 'A' && ch[j] <= 'Z') || (ch[j] >= 'a' && ch[j] <= 'z') )) {
j++;
};
j--;
if (i != j) {
for (int k = i; k <= (j - i) / 2 + i; k++) {
char temp = ch[k];
ch[k] = ch[j - k + i];
ch[j - k + i] = temp;
}
}
i = j;
}
}
return new String(ch);
}
}
✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨
🔥 二、搜索数字(数组 ,二分查找)
package day03.third;
public class Solution {
public static void main(String[] args) {
int [] arr = new int[]{2,6,8,12,10,8};
System.out.println( search(arr , 2) );
}
public static int search (int [] nums , int target){
int start = 0 ;
int end = nums.length - 1 ;
while (start <= end) {
int middle = start + (end - start) / 2 ;
if(nums[middle] == target){
return middle;
}
if(nums[start] <= nums[middle]){
if ( (target >= nums[start]) && target <= nums[middle] ) {
end = middle - 1 ;
}else {
start = start + 1 ;
}
}
if( nums[middle] <= nums[end]){
if(target >= nums[middle] && target<= nums[end]){
start = middle + 1 ;
}else{
end = end - 1 ;
}
}
}
return -1 ;
}
}
✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨
🔥 三、颜色(数组/双指针)
给定一个包含红色、白色、和蓝色,一共n元素的数组, 原地(…)对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排序
package day03.second;
import java.util.Arrays;
public class Solution {
public static void sortColors (int [] nums) {
int low = 0;
int high = nums.length - 1;
int i = 0;
if (i <= high) {
int temp = nums[i];
nums[i] = nums[low];
nums[low] = temp;
++low;
++i;
} else if (nums[i] == 1) {
++i;
} else if (i < high && nums[i] == 2) {
int temp = nums[i];
nums[i] = nums[high];
nums[high] = temp;
--high;
}
}
}