zoukankan      html  css  js  c++  java
  • Cracking the coding interview--Q1.2

    原文

    Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.

    译文

    用C或者C++实现一个void reverse(char* str)的函数来逆转一个已null终止的字符串

    解答

    在C++里,设置俩指针,一个指向字符串头,一个指向尾,然后每次交换一个字符和,指针分别像中间移就行了。这里借用一下Hawstein(http://hawstein.com/posts/1.2.html的代码好了:

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    void swap(char &a, char &b){
        a = a^b;
        b = a^b;
        a = a^b;
    }
    
    void reverse2(char *s){
        int n = strlen(s);
        for(int i=0; i<n/2; ++i)
            swap(s[i], s[n-i-1]);
    }
    
    void reverse1(char *s){
        if(!s) return;
        char *p = s, *q = s;
        while(*q) ++q;
        --q;
        while(p < q)
            swap(*p++, *q--);
    }
    
    int main(){
        char s[] = "1234567890";
        reverse1(s);
        cout<<s<<endl;
        return 0;
    }

    那么如果在Java里能不能也用同样的方法呢?如果简单的用String并且用到上面相同的方法的话,是不行的。因为String是一个不可变的对象,所以swap其中两个字符并不会真的交换。

    在Java里要实现逆转字符串的话可以用以下的方法:

    public class Main {
    
        public static String reverse(String str) {
            return new StringBuilder(str).reverse().toString();
        }
            
        public static void main(String args[]) {
            String s1 = "i am hawstein.";
            String s2 = "abcdefghijklmnopqrstuvwxyzABCD1234567890";
            System.out.println(reverse(s1));
            System.out.println(reverse(s2));
        }
    }
  • 相关阅读:
    5.4、获取对象信息
    5.3、继承和多态
    JS基础-组成
    js定时器
    js 原型链,继承,闭包,内存,泄露
    flex 布局
    点击导出table表格
    图片利用 new Image()预加载原理 和懒加载的实现原理
    js控制style样式
    自定义指令的用法
  • 原文地址:https://www.cnblogs.com/giraffe/p/3185974.html
Copyright © 2011-2022 走看看