字符串删减
给定一个由 n个小写字母构成的字符串。
现在,需要删掉其中的一些字母,使得字符串中不存在连续三个或三个以上的 x。
请问,最少需要删掉多少个字母?
如果字符串本来就不存在连续的三个或三个以上 x,则无需删掉任何字母。
输入格式
第一行包含整数 n。
第二行包含一个长度为 n的由小写字母构成的字符串。
输出格式
输出最少需要删掉的字母个数。
数据范围
3≤n≤100
输入样例1:
6
xxxiii
输出样例1:
1
输入样例2:
5
xxoxx
输出样例2:
0
输入样例3:
10
xxxxxxxxxx
输出样例3:
8
算法思路
首先是定义一个变量cnt记录当前连续出现的字符的x的个数;
每出现一个字符x,cnt加一;
所出现一个其他的字符,则cnt直接清零;
当cnt=3,表示连续出现了3个x,这个时候就需要清除一次cnt,让cnt–,然后继续遍历。
C++
#include<bits/stdc++.h> using namespace std; int main() { int n; string s; cin >> n >> s; int res = 0, cnt = 0; for (int i = 0; i < n; ++ i) { if (s[i] == 'x') { cnt ++; if (cnt == 3) { res ++; cnt --; } } else { cnt = 0; } } cout << res << endl; return 0; }
Java
import java.util.*; public class Main { public static void main(String[] args) { int n; String s; Scanner in = new Scanner(System.in); n = in.nextInt(); s = in.next(); char [] chars = s.toCharArray(); int res = 0, cnt = 0; for (int i = 0; i < n; ++ i) { if (chars[i] == 'x') { cnt ++; if (cnt == 3) { res ++; cnt --; } } else { cnt = 0; } } System.out.println(res); } }