每日小题—Day_1
1、统计回文
/*
- 回文统计
- 判断回文:首先将用户输入的字符串变成一个个的char,
- 一个指针从前往后遍历的同时另一个指针从后往前遍历
- 当发现字符不相等时说明不是回文
- 找插入的位置:知道如何判断回文以后我们只需要将第二个字符串从第一个字符串的
- 第一个位置开始尝试插入,直到判断回文的方法返回true时即找到插入位置
- */
public class Huiwen {
public static boolean isHuiwen(String s){
int i = 0;
int j = s.length()-1;
while (i < j){
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
int count = 0;
for (int i = 0; i < str1.length(); i++) {
StringBuilder sb = new StringBuilder(str1);
sb.insert(i,str2);
if (isHuiwen(sb.toString())){
count++;
}
}
System.out.println(count);
}
}
2、寻找第K大
/*
- 寻找第K大
- 采用快排的思想
- 1.进行一次快排(将大的元素放在前半段,小的元素放在后半段)假设得到的中轴是p
- 2.判断p-low+1 == k,如果成立,直接输出a[p].(因为前半段有k-1个大于a[p]的元素,所以a[p]是第k大的元素)
- 3.如果p-low+1 > k,则第K大的元素在前半段,此时更新high = p-1,继续步骤1
- 4.如果p-low+1 < k,则第K大的元素在后半段,此时更新low = p+1,且k=k-(p-low+1),继续步骤1
*此方法每次可以去掉“一半”的元素,故实际的复杂度不是O(nlgn),而是o(n)
- */
import java.util.Scanner;
public class Finder {
public int findKth(int[] a,int n,int K){
return findKth(a,0,n-1,K);
}
public int findKth(int[] a, int low,int high,int k){
int part = partation(a,low,high);
if (k == part-low+1){
return a[part];
}else if (k > part-low+1){
return findKth(a,part+1,high,k-part+low-1);
}else {
return findKth(a,low,part - 1,k);
}
}
public int partation(int[] a, int low, int high){
int key = a[low];
while (low < high){
while (low<high && a[high] <= key){
high--;
}
a[low] = a[high];
while (low < high && a[low] >= key){
low++;
}
a[high] = a[low];
}
a[low] = key;
return low;
}
}