#hackerrank#Alternating Characters#algorithm#알고리즘

2020. 6. 30. 22:32algorithm

목차

    You are given a string containing characters  and  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.

    For example, given the string s = AABAAB , 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. It must return an integer representing the minimum number of deletions to make the alternating string.

    alternatingCharacters has the following parameter(s):

    • s: a string

    Input Format

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

    Constraints

    • 1 <= q <= 10
    • 1 <= |s| <= 10^5
    • Each string  will consist only of characters  A and B

    Output Format

    For each query, print the minimum number of deletions required on a new line.

    Sample Input

    5

    AAAA

    BBBBB

    ABABABAB

    BABABA

    AAABBB

    Sample Output

    3

    4

    0

    0

    4

    Explanation

    The characters marked red are the ones that can be deleted so that the string doesn't have matching consecutive characters.

     

    problem link : 

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

     

    Alternating Characters | HackerRank

    Calculate the minimum number of deletions required to convert a string into a string in which consecutive characters are different.

    www.hackerrank.com

    * 해결전략

    1) 맨 뒤에서 앞으로 문자를 지운다고 생각을 전환하자.

    2) 현재 문자와 앞 문자가 같으면 현재 문자를 지운다. 

     

    * source code

     

    static int alternatingCharacters(String s) {
            int n = s.length();
            int deleteCount = 0;
    
            for (int i = n - 1; i > 0; i--) {
                if (s.charAt(i) == s.charAt(i - 1)) {
                    deleteCount++;
                }
            }
            return deleteCount;
        }

    'algorithm' 카테고리의 다른 글

    시간 복잡도  (0) 2021.01.29
    #hackerrank#The Grid Search#algorithm#알고리즘  (0) 2020.06.30
    #hackerrank#Making Anagrams#algorithm#알고리즘  (0) 2020.06.30