Java实现字符串反转【Leetcode】

Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

class Solution {
    public void reverseString(char[] s) {
        for (int i = 0;i < s.length;i++) {
            int k = s.length - i - 1;
            if (k < s.length / 2) break;
            char ch = s[i];
            s[i] = s[k];
            s[k] = ch;
        }
    }
}

public class ReverseString {
    public static void main(String[] args) {
        String str = "hello";
//        StringBuilder sb = new StringBuilder(str);
//        String re = sb.reverse().toString(); /// StringBuilder有reverse方法
        char[] s = str.toCharArray();
//        String tp  = String.valueOf(t);
        Solution solution = new Solution();
        solution.reverseString(s);
    }
}
posted @   LeonWen  阅读(453)  评论(0编辑  收藏  举报
努力加载评论中...
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
点击右上角即可分享
微信分享提示