最近无聊在leetcode做了几道String的题,主要是String 反转,虽然用StringBuider 调用reverse就行了,还是自己实现了一下。
题目一、反转字符串
传送门:这里
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
关键代码:
public String reverseString(String s) {
char[] a = s.toCharArray();
int len = a.length;
for(int i=0;i<len/2;i++){
char t =a[i];
a[i]=a[len-1-i];
a[len-1-i]=t;
}
return new String(a);
}
题目二、反转字符串3
传送门:这里
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
代码:分割一下就行了,再按上面的办法反转
class Solution {
public String reverseWords(String s) {
String[] arr =s.split(" ");
StringBuilder sb = new StringBuilder();
for(int i=0;i<arr.length;i++){
if(i!=arr.length-1)
sb.append(reverse(arr[i])+" ");
else{
sb.append(reverse(arr[i]));
}
}
return sb.toString();
}
public String reverse(String str){
char[] a = str.toCharArray();
for(int i=0;i<a.length/2;i++){
char t =a[i];
a[i]=a[a.length-i-1];
a[a.length-i-1]=t;
}
return new String(a);
}
}
题目三、对换字符串中的元音字符
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = “hello”, return “holle”.
Example 2:
Given s = “leetcode”, return “leotcede”.
Note:
The vowels does not include the letter “y”.
题目传送门:这里
class Solution {
public String reverseVowels(String str) {
if(str==null||str.equals("")) return str;
char[] a =str.toCharArray();
int s=0;
int e=a.length-1;
boolean flag=true;
while(flag){
while(!find(a[s])) {
s++;
if(s>=e){
flag=false;
break;
}
}
while(!find(a[e])) {
e--;
if(s>=e){
flag=false;
break;
}
}
if(flag){
char t=a[s];
a[s]=a[e];
a[e]=t;
s++;
e--;
if(s>=e){
flag=false;
break;
}
}
}
return new String(a);
}
public boolean find(char c){ //查找元音字符
if(c=='a'||c=='i'||c=='o'||c=='u'||c=='e'||c=='A'||c=='I'||c=='O'||c=='U'||c=='E'){
return true;
}
return false;
}
}
吐槽:它给的例子元音是小写的 ,只写了小写的,考虑不周吧。