JAVA算法:统计给定字符串中的GFG — 动态规划

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/seagal890/article/details/89602495

统计给定字符串中的GFG(Count of ‘GFG’ Subsequences in the given string)

给定一个长度为n的大写字符串。你的任务是统计其中子序列 ‘GFG’ 出现的次数。

举例说明: 

例如给定字符串 : str[] = "GFGFG"

统计输出结果 : 4

GFGFG, GFGFG, GFGFG, GFGFG

例如给定字符串 : str[] = "ABCFGFPG"

统计输出结果 : 1

算法分析

要在给定的字符串中找到“g f g”子序列的数目,请观察每个“f”,如果我们知道“g”前后的数目。那么“f”的“g f g”子序列数等于“f”前后“g”数的乘积。

因此,我们的想法是维护一个数组arr[],其中arr[i]在索引i之前存储“g”的编号,如果字符串的第i个字符是“f”,在索引i之前存储“f”的编号,如果第i个字符是“g”。

此外,每当遇到“g”时,我们将计算并存储结果中“gfg”子序列的数目。

算法设计

package com.bean.algorithm.basic;

public class GFG {
	static int max = 100;

	// Print the count of "GFG" subsequence
	// in the string
	static void countSubsequence(String s, int n) {
		int[] arr = new int[max];
		int cntG = 0, cntF = 0, result = 0;

		// Traversing the given string
		for (int i = 0; i < n; i++) {
			switch (s.charAt(i)) {

			// If the character is 'G',
			// increment the count of 'G',
			// increase the result and
			// update the array.
			case 'G':
				arr[i] = cntF;
				result += arr[i];
				cntG++;
				break;

			// If the character is 'F',
			// increment the count of 'F'
			// and update the array.
			case 'F':
				arr[i] = cntG;
				cntF += arr[i];
				break;

			// Ignore other character.
			default:
				continue;
			}
		}

		System.out.println(result);
	}

	// Driver code
	public static void main(String args[]) {
		String s = "GFGFG";
		int n = s.length();
		countSubsequence(s, n);
	}
}

猜你喜欢

转载自blog.csdn.net/seagal890/article/details/89602495