- Reverse String
Given s = “hello”, return “olleh
public class Solution {
public String reverseString(String s) {
char[] array = s.toCharArray();//先把STRING转化为char[]
int i = 0;//首
int j = s.length() - 1 ;//末尾
char temp;
// 逆转字符数组
while (i < j){//首尾换位
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
// 利用逆转的字符数组构造最终的逆转字符串
return new String(array);//新的string
}
}
- Reverse Vowels of a String
Given s = “hello”, return “holle”.
public class Solution {
public String reverseVowels(String s) {
String vowels = "aoeiuAOEIU";
char[] a = s.toCharArray();
int i = 0;
int j = a.length - 1;
while (i < j) {
while (i < j && !vowels.contains(a[i] + "")) {
i++;
}
while (i < j && !vowels.contains(a[j] + "")) {
j--;
}
if (i < j) {
char c = a[i];
a[i++] = a[j];
a[j--] = c;
}
}
return new String(a);
}
}
- Reverse Words in a String
Given s = “the sky is blue”,
return “blue is sky the”.
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] array = s.split(" ");//把String 按空格分ARRAY
StringBuilder sb = new StringBuilder();
for (int i = array.length - 1; i >= 0; --i) {//从最后一位到第一位循环
if (!array[i].equals("")) {//当元素不是空格的时候
sb.append(array[i]).append(" ");
//在SB上加上元素,后面加上空格
}
}
//remove the last " "
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
- Reverse Integer
Example1: x = 123, return 321
Example2: x = -123, return -321
public class Solution {
public int reverse(int x) {
//输出结果定义为long
long sum=0;
while (x!=0)
{
int s=x%10;//余数
sum=sum*10+s;
x=x/10;
}
//防止溢出操作
if (sum>Integer.MAX_VALUE||sum<Integer.MIN_VALUE)
{
return 0;
}
return (int)sum;
}
}
- Reverse Linked List
public class Solution {
public ListNode reverseList(ListNode head) { //recursively
if (head == null){
return head;
}
ListNode nextNode = head.next;
head.next = null;
while (nextNode!=null){
ListNode nextNextNode = nextNode.next;
nextNode.next = head;//换位
head = nextNode;
nextNode = nextNextNode;
}
return head;
}
}
把STRING转化为Array
char[] array = s.toCharArray();
String[] array = s.split(” “);
翻转:
找到要换位的点然后SWAP
翻转,删除,查找,排序