Leetcode之Reverse Words in a String

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;
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值