leetCode 49.Anagrams (回文构词法) 解题思路和方法

Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

思路:这题要是解,必须知道什么是回文构词法。所谓回文构词法就是把一个单词的顺序调整,形成新的单词,如”eat“,"tea"就是回文构词法。

所以回文构词法一定是相同的字母不同的顺序,而且最少有两个单词。

本题是将单词排序之后运用set查看是否重复,来判断是否回文构词。具体代码如下:

public class Solution {
    public List<String> anagrams(String[] strs) {
        List<String> list = new ArrayList<String>();
        if(strs.length <= 1){
            return list;
        }
        Map<String,Integer> map = new HashMap<>();
        Set<String> set = new HashSet<>();
        boolean[] b = new boolean[strs.length];//为每个字符串标记,初始均为false
        //处理字符串,变成有序的字符数组
        for(int i = 0; i < strs.length;i++){
        	char[] c = strs[i].toCharArray();
        	Arrays.sort(c);
        	StringBuffer sb = new StringBuffer();
        	for(char k:c){
        		sb.append(k);//将char数组转换成字符串
        	}
        	if(!set.add(sb.toString())){//里面已经存在相同的字符数组
        		list.add(strs[i]);
        		int index = map.get(sb.toString());
        		if(!b[index]){//还没有添加到list
        			list.add(strs[index]);
        			b[index] = true;//将标记置为true,
        		}
        	}else{
        		map.put(sb.toString(),i);//保存首次出现的字符串的索引i
        		set.add(sb.toString());//保存set,下次判断是否重复
        	}
        }
        return list;
    }
}

本题在开始写的代码很繁琐,如下,作为参考,没有用set判断,所以很繁琐,效率也不高。

public class Solution {
    public List<String> anagrams(String[] strs) {
        List<String> list = new ArrayList<String>();
        if(strs.length <= 1){
            return list;
        }
        Map<Integer,char[]> map = new HashMap<>();
        //处理字符串,变成有序的字符数组
        for(int i = 0; i < strs.length;i++){
        	char[] c = strs[i].toCharArray();
        	Arrays.sort(c);//排序
        	map.put(i, c);
        }
        boolean[] b = new boolean[strs.length];//为每个字符串标记,初始均为false
        for(int k = 0; k < strs.length -1 ; k++){
            if(!b[k]){//没有被标记
                 char[] c0 = map.get(k);//假定第k个字符串是回文构词
                 for(int i = k + 1; i < strs.length;i++){//从i=1开始
                     if(!b[i] && c0.length == strs[i].length()){//没有被判断是,且与c0字符数相等
                         char[] c1 = map.get(i);//数组化
                         int j = 0;
                         while( j < c0.length){
                             if(c0[j] != c1[j]){
                                 break;//如果不相同直接break
                             }else{
                                 j++;//相同+1
                             }
                         }
                         if(j == c0.length){//说明字全部相同
                             list.add(strs[i]);
                             b[k] = true;//开始那个也要标记
                             b[i] = true;//标记已是
                         }
                     }
                }
                 if(b[k]){//如果初始已标记,则在list加上
                	 list.add(strs[k]);
                 }
            }
        }
        return list;
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-28 12:49:36

leetCode 49.Anagrams (回文构词法) 解题思路和方法的相关文章

Leetcode:Anagrams 回文构词法

戳我去解题 Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. Anagram(回文构词法)是指打乱字母顺序从而得到新的单词 回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序.因此,将几个单词按照字母顺序排序后,若它们相等,则它们属于同一组anagrams class Solution {

leetCode 27.Remove Element (删除元素) 解题思路和方法

Remove Element Given an array and a value, remove all instances of that value in place and return the new length. The order of elements can be changed. It doesn't matter what you leave beyond the new length. 思路:此题和26题一脉相承,算法上不难,具体如代码所示: public class

leetCode 51.N-Queens (n皇后问题) 解题思路和方法

N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configur

leetCode 57.Insert Interval (插入区间) 解题思路和方法

Insert Interval Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], i

leetCode 22.Generate Parentheses (生成括号) 解题思路和方法

Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "

leetCode 39.Combination Sum(组合总和) 解题思路和方法

Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (includi

leetCode 86.Partition List(分区链表) 解题思路和方法

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1->4->3->

leetCode 75.Sort Colors (颜色排序) 解题思路和方法

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and bl

leetCode 66.Plus One (+1问题) 解题思路和方法

Plus One Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. 思路:给定一个数组,表示一个数,然后返回+1的值.主要就是进位的问题,代码如下: public class Solution { pu