151. 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
".
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
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(); } }
61. Rotate List
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; } }
189. Rotate Array
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.
Hint:
Could you do it in-place with O(1) extra space?
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; } } }
时间: 2024-10-25 16:16:52