leetcode---简单

泄露秘密 提交于 2020-10-24 14:46:43
两数相加

地址:https://leetcode-cn.com/problems/two-sum/

public int[] twoSum(int[] nums,int target){
        for (int i=0;i<nums.length;i++){
            for (int j=i+1;j<nums.length;j++){
                if (nums[i]+nums[j]==target){
                    return  new int[]{i,j};
                }
            }
        }
        return new int[]{-1,-1};
}
判断指标括号

地址:https://leetcode-cn.com/problems/valid-parentheses/

    private static  HashMap<Character,Character> characterHashMap;
    public Solution(){
        characterHashMap = new HashMap<Character, Character>();
        characterHashMap.put(')', '(');
        characterHashMap.put('}', '{');
        characterHashMap.put(']', '[');
    }
    public   boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i=0 ;i<s.length();i++){
            Character character = s.charAt(i);
            if ( characterHashMap.containsKey(character) && !stack.isEmpty() && stack.peek() == characterHashMap.get(character)) {
                stack.pop();
            }else {
                stack.push(character);
            }
        }
        return  stack.isEmpty();
    }

罗马数字转整数

地址 : https://leetcode-cn.com/problems/roman-to-integer/

class Solution {
    
    private HashMap<Character,Integer> hashMap = new HashMap();

    public Solution(){
        hashMap.put('I',1);
        hashMap.put('V',5);
        hashMap.put('X',10);
        hashMap.put('L',50);
        hashMap.put('C',100);
        hashMap.put('D',500);
        hashMap.put('M',1000);
        /**
         * I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
         * X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 
         * C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
         */
        hashMap.put('!',4);
        hashMap.put('@',9);
        hashMap.put('#',40);
        hashMap.put('$',90);
        hashMap.put('%',400);
        hashMap.put('^',900);

    }


    public int romanToInt(String s) {
        if (s == null) {
            return 0;
        }
        String s1 = s.replace("IV","!")
                     .replace("IX","@")
                     .replace("XL","#")
                     .replace("XC","$")
                     .replace("CD","%")
                     .replace("CM","^");
        int sum = 0;
        for (int i = 0; i < s1.length(); i++){
            sum = sum + hashMap.get(s1.charAt(i));
        }
        return sum;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!