leetcode刷题记录

01-two num 2023.03.13

12-整转罗马数字

class Solution {
    public String intToRoman(int num) {
        int[] nums = new int[] {1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String[] strs = new String[] {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        StringBuilder res = new StringBuilder();
        int count = 0;
        while(num > 0) {
            while(num - nums[count] >= 0) {
                res.append(strs[count]);
                num -= nums[count];
            }
            count++;
        }
        return res.toString();
    }
}

03-无重复字符的最长子串

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Map<Character,Integer> map = new HashMap<>();
        int ans = 0;
        int left=0,right=0;
        int n = s.length();
        while(right<n){
            //一旦出现重复字符,就结算不重复子串长度
            if(map.containsKey(s.charAt(right))){
                ans = Math.max(ans,right-left);
                //left变为引起重复字符位置的下一个位置map.get(s.charAt(right))+1
                //用上max方法是为了避免left指针回退,对应用例"abba"
                left = Math.max(left,map.get(s.charAt(right)) + 1);
            }
            // System.out.println("ans:"+ans+",left:"+left+",right:"+right);    
            //<当前字符,字符出现下标>
            map.put(s.charAt(right),right);
            right++;
        }
        //多算一次,是因为有可能整个字符串s都不重复,ans=0
        ans = Math.max(ans,right-left);
        return ans;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法)