一些简单的算法题(一)

###1.将两个有序链表合并为一个新的有序链表并返回,新链表是通过拼接给定的两个链表的所有节点组成的

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode l1Current = l1;
        ListNode l2Current = l2;
        if (null == l1Current) return l2Current;
        if (null == l2Current) return l1Current;
        ListNode head = null;
        if (l1Current.val < l2Current.val) {
            head = l1Current;
            l1Current = l1Current.next;
        } else {
            head = l2Current;
            l2Current = l2Current.next;
        }
        ListNode current = head;
        while (null != l1Current && null != l2Current) {
            if (l1Current.val < l2Current.val) {
                current.next = l1Current;
                l1Current = l1Current.next;
            } else {
                current.next = l2Current;
                l2Current = l2Current.next;
            }
            current = current.next;
        }
        if (null == l1Current) current.next = l2Current;
        if (null == l2Current) current.next = l1Current;
        return head;
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

###2.给定一个包括"(",")","{","}","[","]"的字符串,来判断字符串是否有效,即括号匹配
(利用栈实现)

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class Solution {
    private static final Map<String, String> MAP = new HashMap<String, String>();
    static {
        Solution.MAP.put(")", "(");
        Solution.MAP.put("}", "{");
        Solution.MAP.put("]", "[");
    }
    public boolean isValid(String s) {
        if (null == s)
            throw new NullPointerException("s is null");
        if ("".equals(s)) return true;
        Stack<String> stack = new Stack<String>();
        for (int i = 0; i < s.length(); i++) {
            String now = s.substring(i, i + 1);
            if (!Solution.MAP.containsKey(now))
                stack.push(now);
            else {
                if (stack.size() == 0) return false;
                String last = stack.pop();
                if (!Solution.MAP.get(now).equals(last)) return false;
            }
        }
        return stack.size() == 0;
    }
}

###3,字符串在文件中出现的次数

import java.io.BufferedReader;
import java.io.FileReader;
public class Test {
    public static int countWordInFile(String filename, String word) {
        int count = 0;
        try (FileReader fr = new FileReader(filename)) {
            try (BufferedReader br = new BufferedReader(fr)) {
                String line = null;
                while ((line = br.readLine()) != null) {
                    int index = -1;
                    while (line.length() >= word.length() && (index = line.indexOf(word)) >= 0) {
                        count++;
                        line = line.substring(index + word.length());
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }
    public static void main(String[] args) {
        System.out.println(countWordInFile("e:\\blog\\test\\temp.txt", "public"));
    }
}

所有DNA由一系列缩写为A,C,G和T的核苷酸组成,例如:“ACGAATTCCG”。在研究DNA时,有时识别DNA中的重复序列是有用的。
编写一个函数来查找DNA分子中不止一次出现的所有10个字母长的序列(子串)。

例:
输入: s =“AAAAACCCCAAAAACCCCCCAAAAAGGGTTT”
输出: [“AAAAACCCCC”,“CCCCCAAAAA”]

HashSet不能添加重复字符串

public List<String> findRepeatedDnaSequences(String s) {
    Set seen = new HashSet(), repeated = new HashSet();
    for (int i = 0; i + 9 < s.length(); i++) {
        String ten = s.substring(i, i + 10);
        if (!seen.add(ten))
            repeated.add(ten);
    }
    return new ArrayList(repeated);
}

你是一个专业的强盗,计划在街上抢劫房屋。每个房子都藏着一定数量的钱,阻止你抢劫他们的唯一限制因素是相邻的房屋有连接的安全系统,如果两个相邻的房子在同一个晚上被闯入,它将自动联系警方。
给出一个代表每个房子的金额的非负整数列表,确定今晚可以抢劫的最大金额而不警告警察。

例:
输入: [1,2,3,1]
输出: 4
说明:抢房子1(钱= 1)然后抢房子3(钱= 3)。
您可以抢夺的总金额= 1 + 3 = 4。

//Java自上而下的DP
    public int rob(int[] nums) {
        int[] dp = new int[nums.length];
        Arrays.fill(dp, -1);
        
        return rob(nums, 0, dp);
    }
    
    int rob(int[] nums, int start, int[] dp) {
        if(start >= nums.length)
            return 0;
        
        if(dp[start] != -1)
            return dp[start];
        
        dp[start] = Math.max(nums[start] + rob(nums, start + 2, dp), rob(nums, start + 1, dp));
        return dp[start];
    }

给定一个字符串s,您可以通过在其前面添加字符将其转换为回文结构。通过执行此转换查找并返回您可以找到的最短回文。

例:输入:“aacecaaa”
输出: “aaacecaaa”

基本想法:从第一个索引找到最长的回文

public String shortestPalindrome(String s) {
    if(s.length() == 0) return "";
    int len = s.length(), left, right,  maxLen = 0;
    for(int i = 0 ; i < len;){
        left = right = i;
        while(right < len - 1 && s.charAt(right) == s.charAt(right + 1))
            right ++;
        
        i = right + 1;
        
        while(left > 0 && right < len - 1 && s.charAt(left - 1) == s.charAt(right + 1)){
            left --;
            right ++;
        }
        
        if(left == 0 && maxLen < right + 1){
            maxLen = right + 1;
        }
    }
    
    String prefix = new StringBuilder(s.substring(maxLen)).reverse().toString();

    return prefix + s;
}

给定一个非负整数数组,您最初定位在数组的第一个索引处。
数组中的每个元素表示该位置的最大跳转长度。
确定您是否能够到达最后一个索引。

例1:
输入: [2,3,1,1,4]
输出: true
说明:从索引0跳转1步到1,然后从最后一个索引跳3步。
例2:
输入: [3,2,1,0,4] 输出: false
说明:无论如何,
您总是会到达索引3。它的最大值
跳转长度为0,这使得无法到达最后一个索引。

只需从头到尾扫描nums数组并存储可以达到的最新索引即可

class Solution {
    public boolean canJump(int[] nums) {
        int maxCanJumpTo = 0;
        for (int i = 0; i < nums.length; i++)
        {
            if (maxCanJumpTo < i)
                return false;
            if (maxCanJumpTo == nums.length - 1)
                break;
            maxCanJumpTo = Math.max(maxCanJumpTo, i + nums[i]);
        }
        return true;
    }
}

给定表示图像灰度的2D整数矩阵M,您需要设计更平滑的以使每个单元的灰度变为所有8个周围单元及其自身的平均灰度(向下舍入)。如果一个细胞的周围细胞少于8个,那么尽可能多地使用细胞

输入:
[[1,1,1],
[1,0,1],
[1,1,1]]
输出:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
说明:
对于点(0,0),(0,2),(2,0),(2,2):floor(3/4)= floor(0.75)= 0
对于点(0,1),(1,0),(1,2),(2,1):floor(5/6)= floor(0.83333333)= 0
对于点(1,1):floor(8/9)= floor(0.88888889)= 0
注意:
给定矩阵中的值在[0,255]范围内。
给定矩阵的长度和宽度在[1,150]的范围内。

public class Image {

    public int[][] image(int[][] M) {
        if (M == null) return null;
        int rows = M.length;
        if (rows == 0) return new int[0][];
        int cols = M[0].length;

        int result[][] = new int[rows][cols];

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                int count = 0;
                int sum = 0;
                for (int incR : new int[]{-1, 0, 1}) {
                    for (int incC : new int[]{-1, 0, 1}) {
                        if (isValid(row + incR, col + incC, rows, cols)) {
                            count++;
                            sum += M[row + incR][col + incC];
                        }
                    }
                }
                result[row][col] = sum / count;
            }
        }

        return result;

    }

    private boolean isValid(int x, int y, int rows, int cols) {
        return x >= 0 && x < rows && y >= 0 && y < cols;
    }
}

给定一个字符串和一个整数k,你需要反转从字符串开头算起的每2k个字符的前k个字符。如果剩下少于k个字符,则反转所有字符。如果小于2k但大于或等于k个字符,则反转前k个字符并将另一个字符保留为原始字符

输入: s =“abcdefg”,k = 2
输出: “bacdfeg”
限制:
该字符串仅包含较低的英文字母。
给定字符串的长度和k将在[1,10000]范围内

public class Solution {
    public String reverseStr(String s, int k) {
        char[] arr = s.toCharArray();
        int n = arr.length;
        int i = 0;
        while(i < n) {
            int j = Math.min(i + k - 1, n - 1);
            swap(arr, i, j);
            i += 2 * k;
        }
        return String.valueOf(arr);
    }
    private void swap(char[] arr, int l, int r) {
        while (l < r) {
            char temp = arr[l];
            arr[l++] = arr[r];
            arr[r--] = temp;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值