剑指offer第二版58题的简化版,基于此随便改一下就行没写过java,有什么不合适的欢迎指出githubleetcode时间复杂度O(N)空间复杂度O(N)public class Solution1 { /** * 翻转单词顺序 * @param str * @return */ static public String reverseSentence(String str) { if (str == null || str.length() == 0) { return ""; } char[] chars = str.toCharArray(); //反转每个单词 int i = 0, j = 0; while (j <= chars.length) { if (j == chars.length || chars[j] == ' ') { reverse(chars, i, j - 1); i = j + 1; } j++; } return new String(chars); } /** * 反转char数组 * @param chars * @param start * @param end */ static public void reverse(char[] chars, int start, int end) { while (start < end) { swap(chars, start, end); start++; end--; } } /** * 交换char数组两个位置的值 * @param chars * @param i * @param j */ public static void swap(char[] chars, int i, int j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } public static void main(String []args){ System.out.println(reverseSentence("I am a studnet")); } }
剑指offer第二版58题的简化版,基于此随便改一下就行
没写过java,有什么不合适的欢迎指出
github
leetcode
时间复杂度O(N)
空间复杂度O(N)