7

#yyds干货盘点# 动态规划专题:abb

 1 year ago
source link: https://blog.51cto.com/u_15488507/5848569
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# 动态规划专题:abb

精选 原创

97的风 2022-11-14 11:00:04 博主文章分类:面试题 ©著作权

文章标签 字符串 子序列 字符串长度 文章分类 Java 编程语言 阅读数253

1.简述:

描述

leafee 最近爱上了 abb 型语句,比如“叠词词”、“恶心心”

leafee 拿到了一个只含有小写字母的字符串,她想知道有多少个 "abb" 型的子序列?定义: abb 型字符串满足以下条件:

字符串长度为 3 。

字符串后两位相同。

字符串前两位不同。

输入描述:

第一行一个正整数 #yyds干货盘点# 动态规划专题:abb_字符串长度

第二行一个长度为 #yyds干货盘点# 动态规划专题:abb_字符串长度 的字符串(只包含小写字母)

#yyds干货盘点# 动态规划专题:abb_字符串_03

输出描述:

"abb" 型的子序列个数。

示例1
6
abcbcc
共有1个abb,3个acc,4个bcc
示例2
4
abbb

2.代码实现:

import java.util.*;

public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//输入字符串
String str=sc.next();

//后缀和数组,suffix[i+1][j]表示str中第i个字母之后的对应字母出现次数
int[][] suffix=new int[n+1][26];
for(int i=n-1;i>=0;i--){
char c=str.charAt(i);
for(int j=0;j<26;j++){
suffix[i][j]=suffix[i+1][j];
}
suffix[i][c-'a']++;
}

//记录所有"abb"型子序列的个数
long res=0;

for(int i=0;i<n;i++){
char c=str.charAt(i);
for(int j=0;j<26;j++){
//加上当前字母为前缀,所组成的"abb"型子序列的个数
if(j!=c-'a'&&suffix[i][j]>=2){
res+=suffix[i+1][j]*(suffix[i+1][j]-1)/2;
}
}
}


System.out.println(res);
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK