Reverse a String Without Extra Space Using Bit Manipulation

Sprint reverse can be done in multiple ways such as

  • Using StringBuilder class
  • Iterate String and put in a stack, then create a new String using the Stack pop function.
  • Iterating string in reverse order and creating a new String
  • Iterating and swapping string from both ends using temp variable

Bit Manipulation approach is an extension of Iterating and swapping string from both ends but using temp variable.

Bit manipulation technique is the fast and most suitable way to Reverse a String without using any additional, extra, or auxiliary space.

package org.wesome.dsalgo;

public class StringReverse {
    static String reverse(String string) {
        int start = 0;
        int end = string.length() - 1;
        char[] chars = string.toCharArray();
        while (start < end) {
            chars[start] ^= chars[end];
            chars[end] ^= chars[start];
            chars[start] ^= chars[end];
            ++start;
            --end;
        }
        return String.valueOf(chars);
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class StringReverseTest {
    @Test
    void reverseLowerCase() {
        StringReverse stringReverse = new StringReverse();
        String string = stringReverse.reverse("wesome.org");
        Assertions.assertEquals("gro.emosew", string);
    }

    @Test
    void reverseMixedCase() {
        String reverse = StringReverse.reverse("WeSoMe.OrG");
        Assertions.assertEquals("GrO.eMoSeW", reverse);
    }
}
plugins {
    id 'java'
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on