Alternating Characters

HeeSeong·2021년 6월 29일
0

HackerRank

목록 보기
14/18
post-thumbnail

🔗 문제 링크

https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings


❔ 문제 설명


You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.

Your task is to find the minimum number of required deletions.

Example

Remove an A at positions 0 and 3 to make s = ABAB in 2 deletions.

Function Description

Complete the alternatingCharacters function in the editor below.

alternatingCharacters has the following parameter(s):

  • string s: a string

Returns

  • int: the minimum number of deletions required

Input Format

The first line contains an integer q, the number of queries.
The next q lines each contain a string s to analyze.


⚠️ 제한사항


  • 1q101 ≤ q ≤ 10

  • 1lengthofS1051 ≤ length of S ≤ 10^5

  • Each string s will consist only of characters A and B.



💡 풀이 (언어 : Java)


단순하게 문자열에서 앞뒤로 비교해서 같은 경우만 카운트해주었다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	private static int alternatingCharacters(String s) {
		int count = 0;
		for (int i = 0; i < s.length() - 1; i++) {
			if (s.charAt(i) == s.charAt(i + 1)) {
				count++;
			}
		}
		return count;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		for (int i = 0; i < n; i++) {
			String s = br.readLine();
			System.out.println(alternatingCharacters(s));
		}
		br.close();
	}
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글