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

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

面试题58:翻转字符串

题目一:翻转单词顺序

输入一个英文句子,翻转句子中单词的顺序,但单词内的顺序不变。为简单起见,标点符号和普通字符一样处理。例如,输入字符串"I am a student.",则输出"student. a am I"。

思路:

  1. 按照空格分割字符串。
  2. 将得到的字符串数组倒序输出。

代码实现:

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) {           String[] strs = str.trim().split(" ");        StringBuilder sb = new StringBuilder();        for(int i = strs.length - 1; i >= 0; i--) {               sb.append(strs[i]);            if(i != 0) sb.append(" ");        }        return sb.toString();    }}

题目二:左旋转字符串

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

思路:

  1. 旋转整个字符串
  2. 旋转后两位
  3. 旋转前面5位。

代码实现:

package Question58;public class T02 {       public static void main(String[] args) {           System.out.println(solve("abcdefg", 2));    }    public static String solve(String str, int n) {           String s = "";        for(int i = n; i < n + str.length(); i++) {               s += str.charAt(i % str.length());        }        return s;    }}

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

你可能感兴趣的文章
Nginx+Keepalived实现简单版高可用主备切换
查看>>
nginx+mysql+redis+mongdb+rabbitmq 自动化部署脚本
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
Nginx/Apache反向代理
查看>>
Nginx: 413 – Request Entity Too Large Error and Solution
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
Nginx、HAProxy、LVS
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
nginx中配置root和alias的区别
查看>>