欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 每日OJ题_牛客_mari和shiny_线性dp_C++_Java

每日OJ题_牛客_mari和shiny_线性dp_C++_Java

2025/3/10 5:33:45 来源:https://blog.csdn.net/GRrtx/article/details/142720107  浏览:    关键词:每日OJ题_牛客_mari和shiny_线性dp_C++_Java

目录

牛客_mari和shiny_线性dp

题目解析

C++代码

Java代码


牛客_mari和shiny_线性dp

mari和shiny (nowcoder.com)

描述:
        mari每天都非常shiny。她的目标是把正能量传达到世界的每个角落!
有一天,她得到了一个仅由小写字母组成的字符串。
她想知道,这个字符串有多少个"shy"的子序列?
(所谓子序列的含义见样例说明)


题目解析

简单线性 dp: 维护 i 位置之前,⼀共有多少个 "s" "sh" ,然后更新 "shy" 的个数。

C++代码

#include <iostream>
#include <string>
using namespace std;int main()
{int n = 0;string str;cin >> n >> str;long long s = 0, h = 0, y = 0;for(int i = 0; i < n; i++){char ch = str[i];if(ch == 's'){s++;}else if(ch == 'h'){h += s;}else if(ch == 'y'){y += h;}}cout << y << endl;return 0;
}

Java代码

import java.util.*;
public class Main
{public static void main(String[] args){Scanner in = new Scanner(System.in);int n = in.nextInt();char[] str = in.next().toCharArray();long s = 0, h = 0, y = 0;for(int i = 0; i < n; i++){char ch = str[i];if(ch == 's'){s += 1;}else if(ch == 'h'){h += s;}else if(ch == 'y'){y += h;}}System.out.println(y);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词