344. Reverse String

来源:互联网 发布:淘宝热卖是什么 编辑:程序博客网 时间:2024/05/22 13:08

问题:

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

分析:

1.

public String reverseString(String s) {    byte[] bytes = s.getBytes();    byte temp;    for(int i=0;i<(bytes.length+1)/2;i++){    temp = bytes[i];    bytes[i] = bytes[bytes.length - i - 1];    bytes[bytes.length - i - 1] = temp;    }        return new String(bytes);}
2.贪心算法

public String reverseString(String s) {        char[] word = s.toCharArray();        int i = 0;        int j = s.length() - 1;        while (i < j) {            char temp = word[i];            word[i] = word[j];            word[j] = temp;            i++;            j--;        }        return new String(word);    }





0 0
原创粉丝点击