给定一个仅由小写字母x和y组成且长度不超过105的字符串,每次可以将字符串中的一个子串xy替换成字符串yyx,那么至少要替换多少次才能让字符串中不存在子串xy?
def solution(string): num = 0 count = 0 if string[0] == 'x': count = 1 X = count for i in range(1, len(string)): if string[i] == 'x': X = (2*X+1) % (10 ** 9 + 7) else: num = (num + X) % (10 ** 9 + 7) return int(num % (10 ** 9 + 7)) if __name__ == '__main__': string = raw_input().strip() print(solution(string))
""" 思路: - 题目本质是将x移动到y的后面需要多少次 - 从后往前统计y的数量 - 假设第一次检测到x时,有2个y在后面,x移动需要两次 - 该x移动后y的个数会成倍增长变成2y,所以要将当前y的个数更新为2*y - 依次统计最后得到需要移动的次数,即y的总数 """ import sys strs = input().strip() lens = len(strs) count = 0 res = 0 for i in range(lens-1, -1, -1): if strs[i] == 'y': count += 1 if strs[i] == 'x': res += count count = count*2 print(res % (10**9+7))
#include<iostream>
#include<vector>
#include<string>
#include<math.h>
using namespace std;
const long long mod = pow(10,9) + 7;
int main() {
string str;
cin >> str;
long long pow_2_x = 0;
long long res = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == 'x')
pow_2_x = ((pow_2_x << 1) +1) % mod;
else {
res = (res + pow_2_x) % mod;
}
}
cout << res << endl;
//system("pause");
return 0;
} //思路参考的别的大佬的,java版本
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int len=s.length();
int count=0,res=0;
for(int i=len-1;i>=0;i--){
if(s.charAt(i)=='y'){
count+=1;
}
//要注意数据类型的转换
if(s.charAt(i)=='x'){
res=(res+count)%(1000000007);
count=(count*2)%(1000000007);
}
}
System.out.println(res%(1000000007));
}
}