标签:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
public class Solution { public String reverseWords(String s) { if(s.trim().equals("")) return ""; String[] words = s.split(" "); StringBuilder sb = new StringBuilder(); for(int i = words.length-1; i>=0; --i) { String trimed = words[i].trim(); if(trimed.equals("")) continue; sb.append(trimed); sb.append(" "); } sb.setLength(sb.length()-1); return sb.toString(); } }
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode rotateRight(ListNode head, int n) { if(head == null) return head; int len = 1; ListNode tail = head; while(tail.next!=null) { tail = tail.next; ++len; } int offset = n%len; if(offset == 0) return head; ListNode cut = head; for(int i = 0; i<len-offset-1;++i) cut = cut.next; ListNode newHead = cut.next; cut.next = null; tail.next = head; return newHead; } }
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
public class Solution { public void rotate(int[] nums, int k) { int len = nums.length; k %= len; reverse(nums, 0, len-k-1); reverse(nums, len-k, len - 1); reverse(nums, 0, len - 1); } public void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; ++start; --end; } } }
151. Reverse Words in a String && 61. Rotate List && 189. Rotate Array
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5724487.html