[GeeksForGeeks] Reverse a string without using any temporary variables

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[GeeksForGeeks] Reverse a string without using any temporary variables相关的知识,希望对你有一定的参考价值。

Given a string, reverse it without using any temporary variables.

 

This problem is a variation of the problem swapping two integers without using any temporary variables by XOR.

For integers x and y, to swap them using XOR, we do the following.

x = x ^ y;

y = y ^ x;

x = x ^ y;

Proof of correctness.

y = y ^ (x ^ y) = (y ^ y) ^ x = 0 ^ x = x;

x = (x ^ y) ^ x = (x ^ x) ^ y = 0 ^ y = y;

QED.

Apply this 3 steps XOR operations to each pair of characters that need to be swapped.

 1 public class Solution {
 2     public char[] reverseString(char[] str, int start, int end){
 3         while(start < end){
 4             str[start] ^= str[end];
 5             str[end] ^= str[start];
 6             str[start] ^= str[end];
 7             start++;
 8             end--;
 9         }
10         return str;
11     }
12 }

 

以上是关于[GeeksForGeeks] Reverse a string without using any temporary variables的主要内容,如果未能解决你的问题,请参考以下文章

[GeeksForGeeks] Diameter of a Binary Tree

[GeeksForGeeks] Write a program to delete a tree

平摊分析 Amortized Analysis ------geeksforgeeks翻译

geeksforgeeks@ Maximum Index (Dynamic Programming)

[GeeksForGeeks] Multiply a given integer by 3.5

分析循环 Analysis of Loops-------geeksforgeeks 翻译