字符串及其反转中是否存在同一子字符串
class Solution {
public boolean isSubstringPresent(String s) {
StringBuilder sb = new StringBuilder(s);
String reverse = sb.reverse().toString();
for (int i = 0; i <= s.length() - 2; i++) { // 修改循环终止条件为 <=,以便遍历到倒数第二个字符
if (reverse.contains(s.substring(i, i + 2))) { // 提取子字符串时范围要包括 i 到 i+1
return true;
}
}
return false;
}
}
统计以给定字符开头和结尾的子字符串总数
class Solution {
public long countSubstrings(String s, char c) {
long ans = 0;
char[]chars = s.toCharArray();
long k =1;
for(int i=0;i<s.length();i++){
if(chars[i]==c){
ans=(long)ans+k;
k++;
}
}
return ans;
}
}
成为 K 特殊字符串需要删除的最少字符数
class Solution {
public int minimumDeletions(String word, int k) {
Map<Character,Integer>map = new HashMap<>();
char []chars = word.toCharArray();
Character minCharater = 0;
int v = -1;
int sum = Integer.MAX_VALUE;
for(int i=0;i<word.length();i++ ){
map.putIfAbsent(chars[i],0);
map.put(chars[i],map.get(chars[i])+1);
}
if(map.size()==1||map.size()==0)return 0;
List<Integer> list = new ArrayList<>();
for(Map.Entry<Character,Integer>entry:map.entrySet()){
list.add(entry.getValue());
}
Collections.sort(list);
int m = list.size();
Collections.sort(list);
for(int i = 0; i < m ; i ++){
int temp = -1;
for(int j = 0; j < m ; j ++){
if(i > j){
temp += list.get(j);
}else if(i == j){
continue;
}else{
if(list.get(j) - list.get(i) <= k){
continue;
}else{
temp += list.get(j) - k - list.get(i);
}
}
}
// System.out.println(temp + 1);
// if(temp == -1)continue;
sum = Math.min(sum,temp + 1);
}
return sum;
}
}