【LeetCode】字符串系列(Anagram)

来源:互联网 发布:python snmp模块 编辑:程序博客网 时间:2024/05/22 04:44

49. Group Anagrams

题目:将输入字符串组按组成分类,输出分类好的字符串组

思路:HashMap——设置HashMap,Key为每类字符串按升序排列,Value为该类所有字符串(List<String>)。对于输入的每个字符串,进行字符数组转换,再进行排序,然后转换回字符串,如果HashMap中不包含该类字符串,就建新key,否则将该值加入Value。

public class Solution {    public List<List<String>> groupAnagrams(String[] strs) {        if(strs == null || strs.length < 1) return new LinkedList<List<String>>();        HashMap<String,List<String>> hm = new HashMap<>();        for(String s:strs){            char[] c = s.toCharArray();            Arrays.sort(c);            String ss = String.valueOf(c);            if(hm.containsKey(ss)){                hm.get(ss).add(s);            }            else{                hm.put(ss,new LinkedList<String>());                hm.get(ss).add(s);            }        }        return new LinkedList<List<String>>(hm.values());    }}
242. Valid Anagram

题目:判断两个字符串是不是重组的

思路:新建数组,统计26个字母的个数,第一个对应字符+1,第二个对应字符减1,如果是重组的话,最后该数组所有书为零。

public class Solution {    public boolean isAnagram(String s, String t) {        if(s.length() != t.length()) return false;        int[] c = new int[26];        for(int i = 0; i < s.length(); i++){            c[s.charAt(i)-'a']++;        }        for(int i = 0; i < t.length(); i++){            c[t.charAt(i)-'a']--;        }        for(int i = 0; i < 26; i++){            if(c[i] != 0) return false;        }        return true;    }}

另外,可以类似49的做法,排序后看这两个字符串还等不等。

438. Find All Anagrams in a String

题目:在输入字符串中找到所有重组子串

思路:滑动窗——按照242的方法统计需匹配子串的所有字符次数,用start和end指示目前的窗,count标记还需匹配的个数(匹配一个就减1)

public class Solution {    public List<Integer> findAnagrams(String s, String p) {        List<Integer> ret = new LinkedList<>();        if(p == null || p.length() == 0 || s == null || s.length() == 0) return ret;        int[] c = new int[26];        for(int i = 0; i < p.length(); i++){            c[p.charAt(i)-'a']++;        }        int start = 0, end = 0, count = p.length();        while(end < s.length()){            if(--c[s.charAt(end++)-'a'] >= 0) count--;            if(count == 0) ret.add(start);            if(end-start == p.length() && c[s.charAt(start++)-'a']++ >= 0) count++;        }        return ret;    }}

567. Permutation in String

题目:找到是否存在重组子串

思路:与438题完全相同的方法

public class Solution {    public boolean checkInclusion(String s1, String s2) {        int[] c= new int[26];        for(int i = 0; i < s1.length(); i++){            c[s1.charAt(i)-'a']++;        }        int start = 0, end = 0, count = s1.length();        while(end < s2.length()){            if(--c[s2.charAt(end++)-'a'] >= 0) count--;            if(count == 0) return true;            if(end-start == s1.length() && c[s2.charAt(start++)-'a']++ >= 0) count++;        }        return false;    }}


原创粉丝点击