标签:
今天第一次刷leetcode的题啊,最简单的一题,就出现超时不通过╮(╯▽╰)╭
题目如下:
Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh".
我写的代码是:(真的是最笨的方法╮(╯▽╰)╭)
public static String reverseString(String s) { char[] arrs = s.toCharArray(); String result = ""; for (int i = (arrs.length - 1); i >= 0; i--) { result = result + arrs[i]; } return result; }
提交以后,超时啊~~
public String reverseString(String s) { if(s == null) return null; if(s.equals("")) return s; char[] arrChar = s.toCharArray(); for (int i = 0, j = arrChar.length-1; i <= j; i++, j--) { char temp = arrChar[i]; arrChar[i] = arrChar[j]; arrChar[j] = temp; } return new String(arrChar); }
看了别人的讨论,如下几种方法 Many acceptable answers
Cheating Method using StringBuilder
public class Solution { public String reverseString(String s) { return new StringBuilder(s).reverse().toString(); } }
Classic Method by swapping first and last
public class Solution { public String reverseString(String s) { char[] word = s.toCharArray(); int i = 0; int j = s.length() - 1; while (i < j) { char temp = word[i]; word[i] = word[j]; word[j] = temp; i++; j--; } return new String(word); } }
Same as previous but using byte instead
public class Solution { public String reverseString(String s) { byte[] bytes = s.getBytes(); int i = 0; int j = s.length() - 1; while (i < j) { byte temp = bytes[i]; bytes[i] = bytes[j]; bytes[j] = temp; i++; j--; } return new String(bytes); } }
Classic Method by swapping first and last
If you don‘t like temp variable
public class Solution { public String reverseString(String s) { byte[] bytes = s.getBytes(); int i = 0; int j = s.length() - 1; while (i < j) { bytes[i] = (byte)(bytes[i] ^ bytes[j]); bytes[j] = (byte)(bytes[i] ^ bytes[j]); bytes[i] = (byte)(bytes[i] ^ bytes[j]); i++; j--; } return new String(bytes); } }
Using recursion
public class Solution { public String reverseString(String s) { int length = s.length(); if (length <= 1) return s; String leftStr = s.substring(0, length / 2); String rightStr = s.substring(length / 2, length); return reverseString(rightStr) + reverseString(leftStr); } }
脑子短路ing
标签:
原文地址:http://www.cnblogs.com/yiruparadise/p/5674983.html