Minimum number of operations to make a string amazing.


  • 0
    P

    This is an interview question I've come across but do not remember the words exactly so I am going to paraphrase.

    A string s is said to be Amazing if no two adjacent characters in the string are the same. For example, "a", "ab" "abab", "abcbcb" are all Amazing strings whereas strings such as "abb", "aabb", "abcdeebdcc" are all not Amazing.

    Given a set of words[ ] return the minimum number of operations required to convert the strings to Amazing. Think of one operation as replacing one of the characters in the input string with any character from a-z.
    So to make the string "aabb" amazing, we would need two operations. and to make the string "aaab" amazing, we would need only one operation.

    For Example, for the input:

    String words[] =  { "ab", "aab", "abb", "abab", "abaaaba" };
    

    The output would be:

    0
    1
    1
    0
    1 
    

    Here's the method structure:

    public int[] minimalOperations(String[] words) {
    }
    

  • 0
    P

    @Pramodroy30
    This is my solution: Its a little coarse but I would like to know if there is any input for which this might fail.

    public int[] minimalOperations(String[] words) {
    	int[] result = new int[words.length];
    	for (int i = 0; i < words.length; i++) {
    		String s = words[i];
    		if (s == null || s.isEmpty()) {
    			result[i] = 0;
    			continue;
    		}
    		int count = 0;
    		char[] chars = words[i].toCharArray();
    		int cc = 1;
    		for (int j = 1; j < chars.length; j++) {
    			if (chars[j] == chars[j - 1]) {
    				// count the number of times current character repeats
                                    cc++;
    				if (j == chars.length - 1) {
                                            // special case when last character is repeating
    					count = count + cc / 2;
    				}
    			} else {
    				count = count + cc / 2;
    				cc = 1;
    			}
    		}
    		result[i] = count;
    	}
    	return result;
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.