Leetcode之Reverse Words in a String
来源:互联网 发布:知乎 经典电影 编辑:程序博客网 时间:2024/06/05 20:05
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
题目描述如上:很容易被误导而使用了split方法,对于经常用java的人来说写这种算法题反而有很多坑点,因为有太多api可用了。下面这个方法能通过所有的测试,但是因为时间复杂度高而被否了。原因之一就应该是使用了split等方法而使时间复杂度大于n。
public static String reverseWords(String s) {String[] Splresult = s.split(" ");String result = "";if (Splresult.length <= 2) {int len = s.trim().length();if (len == 0) {return "";} else if (len == 1) {return s.trim();}}int i = 0;for (i = Splresult.length - 1; i > 0; i--) {result += Splresult[i];if (i + 1 < Splresult.length - 1) {result += " ";}}if (!Splresult[i].equals(" ")) {result += Splresult[i];}return result;}
下面这个只用了一个length()方法,而且我还用一个变量把结果进行了存储而防止多次运算。时间复杂度为O(n)。
public static String reverseWords(String s) {String CurStr = "";String result = "";s += " ";int i = 0;int len = s.length();while (i < len) {if (s.charAt(i) != ' ') {CurStr += s.charAt(i);} else if (result.length() == 0) {result = CurStr + result;CurStr = "";} else if (CurStr.length() != 0) {CurStr += " ";result = CurStr + result;CurStr = "";}i++;}return result;}
0 0
- leetcode之Reverse Words in a string
- leetcode之Reverse Words in a String
- leetcode之Reverse Words in a String
- LeetCode之Reverse Words in a String
- Leetcode之Reverse Words in a String
- leetcode之Reverse Words in a String
- Leetcode之Reverse Words in a String
- LeetCode之Reverse Words in a String
- 【Leetcode】之 Reverse Words in a String
- Leetcode - string - Reverse Words in a String
- LeetCode 之 Reverse Words in a String — C 实现
- java中leetcode之Reverse Words in a String
- python:leetcode之reverse words in a string
- LeetCode之路:557. Reverse Words in a String III
- LeetCode之Reverse Words in a String III
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 『HTML5梦幻之旅』 - 跟随歌曲显示当前歌词
- getopt() 函数使用方法
- Visual Basic 语言参考 ------类型转换函数
- $.ajaxSetup 使用
- 将数据窗口保存为Excel文件的方法
- Leetcode之Reverse Words in a String
- DnsApi简单探索(1) DnsQueryEx function
- 关于自定义协议分割字段的实现
- Jmeter 导入Eclipse,如何编译
- 1008. Elevator (20)
- Linux管理默认系统开机启动服务
- mysql数据库__join(行关联)_union(列关联)_minus(集合相减)_intersect(交集)_TRIM(取出空白字符)_ COMMENT(字段加注释)_CONCAT(字段追加内容)
- CentOS 7 下安装 LEMP 服务(nginx、MariaDB/MySQL 和 php)
- 我的2014---感悟程序员职场