首页 > 代码库 > [GeeksForGeeks] Reverse a string without using any temporary variables
[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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。