【平方数之和&反转字符串中的元音字母】
这两道题的用到的算法思想都是双指针
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c 。
示例 1:
输入:c = 5
输出:true
解释:1 * 1 + 2 * 2 = 5
示例 2:
输入:c = 3
输出:false
示例 3:
输入:c = 4
输出:true
示例 4:
输入:c = 2
输出:true
示例 5:
输入:c = 1
输出:true
代码:
class Solution {
public boolean judgeSquareSum(int c) {
int L=0;
int R=(int)Math.sqrt(c);//降低计算量,基操
while(L<=R){
if((L*L+R*R)==c){
return true;
}else if((L*L+R*R)<c){
L++;
}else {
R--;
}
}
return false;
}
}
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入:"hello"
输出:"holle"
示例 2:
输入:"leetcode"
输出:"leotcede"
代码:
public static String reverseVowels(String s) {
char[] target=s.toCharArray();
int L=0;
int R=s.length()-1;
char temp='0';
while(L<R){
if(target[L]=='a'||target[L]=='e'||target[L]=='i'||target[L]=='o'||target[L]=='u'||target[L]=='A'||target[L]=='E'||target[L]=='I'||target[L]=='O'||target[L]=='U'){
if(target[R]=='a'||target[R]=='e'||target[R]=='i'||target[R]=='o'||target[R]=='u'||target[R]=='A'||target[R]=='E'||target[R]=='I'||target[R]=='O'||target[R]=='U'){
temp=target[L];
target[L]=target[R];
target[R]=temp;
L++;
R--;
}else {R--;}
}else {L++;}
}
return new String(target);
}
tips:
字符数组转字符串直接new String(字符数组)得到的就是字符串
return new String(target);