Leetcode: 167. Two Sum II - Input array is sorted (Easy)

从一个已经排序的数组中查找出两个数,使它们的和为 0

Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2

  1. public int[] twoSum(int[] numbers, int target){
  2. int i = 0, j = numbers.length - 1;
  3. while(i < j){
  4. int sum = numbers[i] + numbers[j];
  5. if(sum == target) return new int[]{i + 1, j + 1};
  6. else if(sum < target ) i++;
  7. else j--;
  8. }
  9. return null;
  10. }

Leetcode: 345. Reverse Vowels of a String (Easy)

Given s = “leetcode”, return “leotcede”.

  1. private HashSet<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
  2. public String reverseVowels(String s) {
  3. if(s.length() == 0) return s;
  4. int i = 0, j = s.length() - 1;
  5. char[] result = new char[s.length()];
  6. while(i <= j){
  7. char ci = s.charAt(i);
  8. char cj = s.charAt(j);
  9. if(!vowels.contains(ci)){
  10. result[i] = ci;
  11. i++;
  12. } else if(!vowels.contains(cj)){
  13. result[j] = cj;
  14. j--;
  15. } else{
  16. result[i] = cj;
  17. result[j] = ci;
  18. i++;
  19. j--;
  20. }
  21. }
  22. return new String(result);
  23. }

Leetcode: 633. Sum of Square Numbers (Easy)

Input: 5 Output: True Explanation: 1 1 + 2 2 = 5

public boolean judgeSquareSum(int c) {
    int left = 0, right = (int) Math.sqrt(c);
    while(left <= right){
        int powSum = left * left + right * right;
        if(powSum == c) return true;
        else if(powSum > c) right--;
        else left++;
    }
    return false;
}

Leetcode: 680. Valid Palindrome II (Easy)

Input: “abca” Output: True Explanation: You could delete the character ‘c’.

public boolean validPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while(i < j){
        if(s.charAt(i) != s.charAt(j)){
            return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);
        }
        i++;
        j--;
    }
    return true;
}

private boolean isPalindrome(String s, int l, int r){
    while(l < r){
        if(s.charAt(l) != s.charAt(r))
            return false;
        l++;
        r--;
    }
    return true;
}

补充 Leetcode: 125 Valid Palindrome I (Easy)
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写

    public boolean isPalindrome(String s) {
        StringBuffer sgood = new StringBuffer();
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetterOrDigit(ch)){
                sgood.append(Character.toLowerCase(ch));
            }
        }
        StringBuffer sgood_rev = new StringBuffer(sgood).reverse();
        return sgood.toString().equals(sgood_rev.toString());
    }