Question

For a given string S, the function change (n, m) replaces all 'n' with 'm' in...

For a given string S, the function change (n, m) replaces all 'n' with 'm' in string S. For example, if S = "alopecia", change (a, b) will give the string "blopecib". You need to find the minimum number of uses of change (n, m) such that the string S forms a palindrome. ​ I'm looking for a O(length(S)) solution. Preferably JAVA.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
// Code to copy

// Create class 
public class MinChange
{
    // create method to find the minimum number
    // character change required
    public static void minchange(char[] s)
    {
        // Finding the length of the string  
        int n = s.length;  
  
        // To store the number of replacement operations  
        int count = 0;
        for(int i=0;i<n/2;i++) 
            { 
                
                // If the characters at location i and n-i-1 are same then  
                // no change is needed
                if(s[i]== s[n-i-1])  
                    continue; 
                
                // Counting one change operation  
                count+= 1; 

                // change(n,m) function part
                // Changing the character with higher  
                // ascii value with lower ascii value  
                if(s[i]<s[n-i-1])  
                    s[n-i-1]= s[i] ; 
                else
                    s[i]= s[n-i-1] ; 
            }
        System.out.println("Minimum characters to be replaced = "+count);
        System.out.println(s);
    }

    // create main method (driver code)
    public static void main(String[] args)
    {
        String s = "ceeks";
        char[] schar = s.toCharArray();
        minchange(schar);  
    }
}

// screenshot of the code

// screenshot of the output

// In case of any query, you can ask in comment

// thanks

Add a comment
Know the answer?
Add Answer to:
For a given string S, the function change (n, m) replaces all 'n' with 'm' in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT