Home > OS >  Switching a's and b's in a String Java 7KYU Kata Codewars
Switching a's and b's in a String Java 7KYU Kata Codewars

Time:04-21

Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.

Example:

'acb' --> 'bca'
'aabacbaa' --> 'bbabcabb'

My Code ->

        public class Switch {
        public static String switcheroo(String x) {
        
            char[] arr = x.toCharArray();
         for (int i=0;i<(x.length()-1);i  ){
            if(arr[i]=='a'){
              arr[i]='b';
            }
            else if(arr[i]=='b'){
              arr[i]='a';
            }
          }
        x = String.valueOf(arr);
        
        return x;
      }
    }
  

Im getting an error

expected:<aaabcccbaa[a]> but was:<aaabcccbaa[b]>

I am Unable to figure out this please help. Link to question - https://www.codewars.com/kata/57f759bb664021a30300007d/train/java

CodePudding user response:

The problem ist your loop, when iterating starting at zero only check less than length i < x.lenth(). The "length minus one" is needed when starting with one eg: for (int i = 1; i < (x.length() - 1); i ) .... Since you did both the last char is never iterated over and cannot be changed by the code inside your loop.

for (int i = 0; i < x.length(); i  ) {
    if (arr[i] == 'a') {
        arr[i] = 'b';
    }
    else if (arr[i] == 'b') {
        arr[i] = 'a';
    }
}

CodePudding user response:

It seems your problem comes from your index, your are looping on your array but your code stops at i < (x.length -1). To fix it, you only have to remove the minus one part : i < x.length or i <= (x.length - 1)

CodePudding user response:

you can use the code:

#include <string>
#include <algorithm>
#include <iterator>

std::string switcheroo(const std::string &s) {
  std::string tmp;
  
  std::transform(s.begin(), s.end(), std::back_inserter(tmp), 
                [](const auto& i) {
                  if (i == 'a') { return 'b'; }
                  if (i == 'b') { return 'a'; }
                  return i;
                });
  return tmp;
}
  •  Tags:  
  • java
  • Related