码迷,mamicode.com
首页 > 其他好文 > 详细

[GeeksForGeeks] Reverse a string without using any temporary variables

时间:2017-07-22 09:54:24      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:ora   hat   operation   app   without   following   problem   variable   eps   

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

标签:ora   hat   operation   app   without   following   problem   variable   eps   

原文地址:http://www.cnblogs.com/lz87/p/7220161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!