1768. 交替合并字符串

Untitled

public String mergeAlternately(String word1, String word2) {
    char[] w1 = word1.toCharArray();
    char[] w2 = word2.toCharArray();
    StringBuilder sb = new StringBuilder();
    int s1 = 0, s2 = 0;
    while(s1 < w1.length && s2 < w2.length) {
        sb.append(w1[s1++]);
        sb.append(w2[s2++]);
    }
    while(s1 < w1.length) sb.append(w1[s1++]);
    while(s2 < w2.length) sb.append(w2[s2++]);
    
    return sb.toString();
}

1071. 字符串的最大公因子

Untitled

public String gcdOfStrings(String str1, String str2) {
        // 假设str1是N个x,str2是M个x,那么s1+s2=s2+s1
        if(!(str1 + str2).equals(str2 + str1)) {
            return "";
        }
        // 确实满足条件就进行辗转相除法找 最大公因子
        return str1.substring(0, gcd(str1.length(), str2.length()));
    }
    // 找最大公因子
    private int gcd(int a, int b) {
        if(b == 0) return a;
        else return gcd(b, a % b);
    }

1431. 拥有最多糖果的孩子

Untitled

public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
        List<Boolean> list = new ArrayList<>();
        int max = candies[0];
        for(int x: candies) 
            max = Math.max(max, x);

        for(int i = 0; i < candies.length; i++) {
            if(candies[i] + extraCandies >= max) list.add(true);
            else list.add(false);
        }
        return list;
    }

238. 除自身以外数组的乘积

Untitled

public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] left = new int[n];
    int[] right = new int[n];   
    int[] ans = new int[n];
    
    // 生成左乘积数组
    int k = 1;
    for(int i = 0; i < n; i++) {
        left[i] = k;
        k *= nums[i];
    }
    // 生成右乘积数组
    k = 1;
    for(int i = n - 1; i >= 0; i--) {
        right[i] = k;
        k *= nums[i];
    }

    // 生成答案
    for(int i = 0; i < n; i++) {
        ans[i] = left[i] * right[i];
    }
    return ans;
}

**300. 最长递增子序列(动态规划)**

Untitled

public int lengthOfLIS(int[] nums) {
    int n = nums.length;
    int[] idx = new int[n];
    idx[0] = 1;
    int ans = 1;
    for(int i = 1; i < n; i++) {
        idx[i] = 1;
        for(int j = i - 1; j >= 0; j--) {
            if(nums[i] > nums[j]) 
                idx[i] = Math.max(idx[i], idx[j] + 1);
        }
        ans = Math.max(idx[i], ans);
    }
    return ans;
}

**334. 递增的三元子序列(技巧题)**

Untitled

public boolean increasingTriplet(int[] nums) {
    int n = nums.length;
    int small = Integer.MAX_VALUE, mid = small;
    for(int x: nums) {
        if(x <= small) {
            small = x;
        }else if(x <= mid) {
            mid = x;
        }else {
            return true;
        }
    }
    return false;
}

**443. 压缩字符串(双指针)**

Untitled