1

LeetCode-344-反转字符串

 2 years ago
source link: https://segmentfault.com/a/1190000040711313
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LeetCode-344-反转字符串

发布于 9 月 19 日

反转字符串

题目描述:编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:数组遍历

遍历s,遍历顺序是0~s.length/2,将第i项的值和第s.length-1-i项的值进行交换。遍历完成后的s即为反转后的字符串。

public class LeetCode_344 {
    public static void reverseString(char[] s) {
        for (int i = 0; i < s.length / 2; i++) {
            // 第i项和第s.length-1-i项进行交换
            char temp = s[i];
            s[i] = s[s.length - 1 - i];
            s[s.length - 1 - i] = temp;
        }
    }

    public static void main(String[] args) {
        char[] s = new char[]{'h', 'e', 'l', 'l', 'o'};
        System.out.println("-----反转之前-----");
        for (char c : s) {
            System.out.print(c + " ");
        }
        System.out.println();
        reverseString(s);
        System.out.println("-----反转之后-----");
        for (char c : s) {
            System.out.print(c + " ");
        }
    }
}

【每日寄语】 每一次的突破都是为了成就更好的自己。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK