博客
关于我
剑指offer之面试题58:翻转字符串
阅读量:324 次
发布时间:2019-03-04

本文共 1037 字,大约阅读时间需要 3 分钟。

翻转字符串的任务是将给定句子中的单词顺序倒转,但保持每个单词内部的顺序不变。例如,输入"I am a student.",输出应该是"student. a am I"。下面将详细阐述实现步骤和代码。

实现步骤

  • 处理输入字符串:首先对输入字符串进行trim处理,去除前后空格。
  • 分割单词:使用split("\s+")方法将字符串按空格分割,得到单词数组。
  • 倒序排列单词:将单词数组倒序遍历。
  • 拼接字符串:使用StringBuilder逐个拼接单词,确保每个单词之间有空格。
  • 代码实现

    package Question58;public class T01 {    public static void main(String[] args) {        String str = "  hello world!  ";        System.out.println(solve(str));    }    public static String solve(String str) {        if (str == null || str.isEmpty()) {            return "";        }        String[] words = str.trim().split("\\s+");        StringBuilder sb = new StringBuilder();        for (int i = words.length - 1; i >= 0; i--) {            sb.append(words[i]);            if (i != 0) {                sb.append(" ");            }        }        return sb.toString();    }}

    解释

  • trim处理str.trim()去除字符串前后空格,确保分割后的单词数组不包含空字符串。
  • split方法:利用split("\\s+")按多个空格分割,得到不含空字符串的单词数组。
  • 倒序遍历:从单词数组最后一个元素开始,逐个添加到StringBuilder中。
  • 拼接单词:在逐个添加单词时,检查是否是最后一个单词,决定是否添加空格。
  • 这个方法确保了单词顺序被正确翻转,同时保持每个单词的内部顺序和标点符号不变,有效解决了问题。

    转载地址:http://ijjq.baihongyu.com/

    你可能感兴趣的文章
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>