当前位置:主页 > 软件编程 > JAVA代码 >

剑指Offer之Java算法习题精讲数组与列表的查找及字符串转换

时间:2022-12-28 09:39:57 | 栏目:JAVA代码 | 点击:

题目一

解法

class Solution {
    public String toLowerCase(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<s.length();i++){
            char ch = s.charAt(i);
            if('A'<=ch&&ch<='Z'){
                ch = (char)(ch+32);
            }
            sb.append(ch);
        }
        return sb.toString();
    }
}

题目二

解法

class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0;
        for(int i = 0;i<nums.length;i++){
            sum+=nums[i];
        }
        int left = 0;
        int right = sum;
        for(int i = 0;i<nums.length;i++){
            right = right-nums[i];
            if(i == 0){
                left = 0;
                if(right==left) return 0;
            }else{
                left+=nums[i-1];
                if(right==left){
                    return i;
                }
            }
        }
        return -1;
    }
}

 题目三

 解法

class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i = left;i<=right;i++){
            if(selfDividing) list.add(i);
        }
        return list;
    }
    public boolean selfDividing(int n) {
        for (char c: String.valueOf(n).toCharArray()) {
            if (c == '0' || (n % (c - '0') > 0))
                return false;
        }
        return true;
    }   
}

题目四

 解法

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int left = 0;
        int right = letters.length;
        while(left<right){
            int mid = left+(right-left)/2;
            if(letters[mid]<=target){
                left = mid+1;
            }else{
                right = mid;
            }
        }
        return left==letters.length?letters[0]:letters[left];
    }
}

您可能感兴趣的文章:

相关文章