[LeetCode-Classic Interview 150 Questions-day10]

Table of contents

242. Valid allophones

 49. Alphabet anagram grouping

 202.Happy number

 219. There are repeated elements Ⅱ

 383.Ransom letter

 205. Isomorphic strings

290. Word rules 


 

242. Valid allophones

Question meaning:

Given two strings  s and  t , write a function to determine  t whether is  s an anagram of .

Note: If  each character in s and  t appears the same number of times, then  s and  are said t to be anagrams of each other.

【Input sample】

s="anagram",t="nagaram"

[Output sample] true

Problem-solving ideas:

It's relatively simple. Define an array to record the number of occurrences of letters in two strings.

The array alphaNum is initialized to 0, a string is responsible for its ++, and an alignment--

If it is an anagram, the final value of alphaNum will definitely still be all 0

class Solution {
    public boolean isAnagram(String s, String t) {
        //s和t都是小写字母,每个字符出现次数相同,当两个字符长度不一样时也不行
        if(s.length() != t.length()){
            return false;
        }
        int[] alphaNum = new int[26];
        for(int i=0;i<s.length();++i){
            ++alphaNum[s.charAt(i) - 'a'];
        }
        for(int i = 0;i<t.length();++i){
            --alphaNum[t.charAt(i) - 'a'];
            if(alphaNum[t.charAt(i) - 'a'] < 0){
                return false;
            }
        }
        return true;
    }
}

Time: Beat 82.24%

Memory: Beaten by 71.71%

 49. Alphabet anagram grouping

Question meaning:

You are given an array of strings, and you are asked to  combine the anagrams  together. The list of results can be returned in any order.

An anagram  is a new word obtained by rearranging all the letters of the source word.

【Input sample】

strs=["eat","tea","tan","ate","nat","bat"]

[Output sample][["eat","tea","ate"],["tan","nat"],["bat"]]

Problem-solving ideas:

Sorting + hashing
: Get a string str and sort it: for example, "eat" is "aet" after sorting, and then save aet as a key in the map
using map.getOrDefault(key, new Array<>()) ;
If this key exists in the map, the value corresponding to the key (list in this question) will be returned. If there is no such key, it proves that it is the first time it is encountered, and a new list will be created.

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        //方法一:排序+哈希
        Map<String,List<String>> map = new HashMap<String,List<String>>();
        for(String str: strs){
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);
            List<String> list = map.getOrDefault(key,new ArrayList<String>());
            list.add(str);
            map.put(key,list);
        }
        return new ArrayList<List<String>>(map.values());//把map转成对应格式
    }
}

Time: Beat 99.24%

Memory: Beaten by 40.02%

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        //方法二:计数+哈希
        /**
        拿到一个字符串str,按上一题的思路统计出现的次数和字母作为key:如eat为a1e1t1
        用计数统计来替换掉数组排序
        之后是一样的操作
        使用map.getOrDefault(key,new Array<>());
        如果map中存在此key,会将key对应的value(本题是list)返回了,如果没有此key,证明是第一次遇到,new一个list
         */
        Map<String,List<String>> map = new HashMap<String,List<String>>();
        for(String str: strs){
            int[] count = new int[26];
            for(int i=0;i<str.length();++i){
                ++count[str.charAt(i)-'a'];
            }
            //合成key
            StringBuffer key = new StringBuffer();
            for(int i=0;i<26;++i){
                if(count[i]!=0){
                    key.append((char)(i+'a'));//字母
                    key.append(count[i]);//次数
                }
            }
            String strKey = key.toString();
            List<String> list = map.getOrDefault(strKey,new ArrayList<String>());
            list.add(str);
            map.put(strKey,list);
        }
        return new ArrayList<List<String>>(map.values());//把map转成对应格式
    }
}

 202.Happy number

Question meaning:

Write an algorithm to determine  n whether a number is a happy number.

"Happy Number"  is defined as:

  • For a positive integer, each time the number is replaced by the sum of the squares of its digits at each position.
  • Then repeat this process until the number reaches 1, or it may  loop infinitely  but never reaches 1.
  • If  the result of this process is  1, then this number is the happy number.

If  n it is  a happy number  , return it  true ; if not, return it  false .

【Input sample】n=19

[Output sample] true

Problem-solving ideas:

Hash collection

Continuously calculate the sum of the squares of each digit of n, and store the calculated number each time in the set. If it is found that the currently calculated n is already stored in the set when n is not equal to 1, it proves that it has fallen into an infinite loop.

class Solution {
    private int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }

    public boolean isHappy(int n) {
        Set<Integer> seen = new HashSet<>();
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);
            n = getNext(n);
        }
        return n == 1;
    }
}

 Time: Beat 85.70%

Memory: Beaten by 81.73%

 219. There are repeated elements Ⅱ

Question meaning:

Given an integer array  nums and an integer  k , determine whether there are two  different index sums  in the array  , satisfying   and   . If present, return   ; otherwise, return   . i jnums[i] == nums[j]abs(i - j) <= ktruefalse

[Input example] nums=[1,2,3,1],k=3

[Output sample] true

Problem-solving ideas:

nums[i] serves as key and i serves as value. When nums[j] == nums[i] is found, calculate the difference between i and j. If it does not meet the requirements of k, modify the value of nums[i] to j, because When traversing the array, the pointer keeps going backwards.

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        int temp;
        for(int i=0;i<nums.length;++i){
            temp = nums[i];
            if(map.containsKey(temp) && (i - map.get(temp) <=k)){
               return true;
            }
            map.put(temp,i);
        }
        return false;
    }
}

Time: Beat 85.19%

Memory: Beaten by 47.36%

 383.Ransom letter

Question meaning:

Given two strings: ransomNote and  magazine , determine  ransomNote whether they can  magazine be composed of the characters inside.

Return if possible  true ; otherwise return  false .

magazine Each character in can only  ransomNote be used once in .

hint:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and  magazine consists of lowercase English letters

[Input example] ransomNote="a", magazine = "b"

[Output sample] false

Problem-solving ideas:

Directly count the number of times each character is used in magazine. Can it be greater than or equal to the number of times each character is used in randomNote?

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if(magazine.length() < ransomNote.length()){
            return false;
        }
        int[] num = new int[26];
        for(int i=0;i<magazine.length();++i){
            ++num[magazine.charAt(i) - 'a'];
        }
        for(int i=0;i<ransomNote.length();++i){
            --num[ransomNote.charAt(i) - 'a'];
            if(num[ransomNote.charAt(i) - 'a'] < 0){
                return false;
            }
        }
        return true;
    }
}

Time: Beat 99.33%

Memory: Beats 98.96%

 205. Isomorphic strings

Question meaning:

Given two strings  s and  t , determine whether they are isomorphic.

If  s the characters in can be replaced according to a certain mapping relationship  t , then the two strings are isomorphic.

Each occurrence of a character should be mapped to another character without changing the order of the characters. Different characters cannot be mapped to the same character, the same character can only be mapped to the same character, and characters can be mapped to themselves.

hint:

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s and  t consists of any valid ASCII characters

[Input example] s="egg",t="add"

[Output sample] true

Problem-solving ideas:

s.charAt(i) is the key and t.charAt(i) is the value, which must be consistent.

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s==null){
            return true;
        }
        Map<Character,Character> map = new HashMap<Character,Character>();
        for(int i=0;i<s.length();++i){
            char key = s.charAt(i);
            if(!map.containsKey(key)){
                //如果这个key和value都不存在的话,那就直接添加key,value
                //key不存在,但是已经有value了,也不行
                if(map.containsValue(t.charAt(i))){
                    return false;
                }
                map.put(key,t.charAt(i));
            }else{
                if(t.charAt(i) != map.get(key)){
                    return false;
                }
            }
        }
        return true;
    }
}

Time: Beat 58.80%

Memory: Beaten by 76.72%

290. Word rules 

Question meaning:

Given a pattern  pattern and a string  s , determine  s whether it follows the same pattern.

Follow  here  refers to a complete match. For example,  there is a two-way connection between pattern each letter in and each non-empty word in the string  .s 

hint:

  • 1 <= pattern.length <= 300
  • pattern Contains only lowercase English letters
  • 1 <= s.length <= 3000
  • s Contains only lowercase English letters and ' '
  • s Does not contain  any leading or trailing pairs of spaces
  • s Each word in is  separated by a single space 

[Input example] pattern="abba", s="dog cat cat dog"

[Output sample] true

Problem-solving ideas:

Similar to 205. Isomorphic string, except that the value changes from Character to String.

class Solution {
    public boolean wordPattern(String pattern, String s) {
        if(s == null){
            return true;
        }
        Map<Character,String> map = new HashMap<Character,String>();
        String[] str = s.split(" ");//根据空格提取单词
        if(pattern.length() != str.length){
            return false;
        }
        for(int i=0;i<pattern.length();++i){
            char key = pattern.charAt(i);
            if(map.containsKey(key) && !(str[i].equals(map.get(key)))){
                return false;
            }
            if(!map.containsKey(key) && map.containsValue(str[i])){
                return false;
            }
            map.put(key,str[i]);
        }
        return true;
    }
}

Time: Beat 55.43%

Memory: Beaten by 61.55%

Guess you like

Origin blog.csdn.net/qq_37998848/article/details/132389304