1.判断回文子串
比如:aabcb,回文子串:a、a、aa、b、c、b、bcb
简单算法:可以暴力破解,双层循环,截取字符串,再反转比较
import java.util.*;public class Main {public static void main(String[] args){Scanner sc= new Scanner(System.in);String str = sc.next();int sum=0;for (int i = 0; i < str.length(); i++){for (int j = i+1; j <=str.length(); j++){String str1=str.substring(i, j);if(str1.equals( new StringBuffer(str1).reverse().toString()))sum++;}System.out.println(sum);}}
高级写法:
1.拿到字符串先右看,看是否有aa,aaa,aaaa这种类型的回文子串
2.右看完再右看补充,看有没有abba这种类型的回文子串
3.再根据下标左右看,看是否相等,但是可能会和右看的aaa这种类型重复,所以要比右看的长度长才能算
import java.util.*;public class Main {public static void main(String[] args){Scanner sc= new Scanner(System.in);String[] str = sc.next().split("");int sum=str.length;for (int i = 0; i < str.length; i++){int j=i+1;while (j <str.length)//右看{if (str[i].equals(str[j])){sum++;j++;}elsebreak;}int k=i-1;while (k>=0&&j <str.length)//右看补加{if (str[k].equals(str[j])){sum++;k--;j++;}elsebreak;}int m=i-1;int n=i+1;while (m>=0 && n<str.length)//左看{if (str[m].equals(str[n])&&n>=j){sum++;m--;n++;}elsebreak;}}System.out.println(sum);}}
2.划分字母区间
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。
public static List<Integer> partitionLabels(String s) {int[] last = new int[26];int length = s.length();for (int i = 0; i < length; i++) {last[s.charAt(i) - 'a'] = i;}List<Integer> partition = new ArrayList<Integer>();int start = 0, end = 0;for (int i = 0; i < length; i++) {end = Math.max(end, last[s.charAt(i) - 'a']);if (i == end) {partition.add(end - start + 1);start = end + 1;}}return partition;}
