1. 程式人生 > >leetCode 49.Anagrams (迴文構詞法) 解題思路和方法

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;
    }
}


相關推薦

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. 思路:這題要是解,必須知

leetCode 27.Remove Element (刪除元素) 解題思路方法

value ava leetcode ont bsp lac 方法 -s post Remove Element Given an array and a value, remove all instances of that value in plac

leetCode 57.Insert Interval (插入區間) 解題思路方法

use example ava article urn win time 例如 ont Insert Interval Given a set of non-overlapping intervals, insert a new interval into

leetCode 72.Edit Distance (編輯距離) 解題思路方法

Edit Distance Given two words word1 and word2, find the minimum number of steps required to conve

leetCode 22.Generate Parentheses (生成括號) 解題思路方法

Generate Parentheses  Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For exampl

leetCode 48.Rotate Image (旋轉影象) 解題思路方法

Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees

leetCode 67.Add Binary (二進位制加法) 解題思路方法

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" R

leetCode 51.N-Queens (n皇後問題) 解題思路方法

dex 數據 我想 attack upload sar alt row queen N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such t

leetCode 88.Merge Sorted Array (合並排序數組) 解題思路方法

pub and bsp clas top n) 思想 ava 方法 Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. N

leetCode 47.Permutations II (排列組合II) 解題思路方法

nts 看到了 possible ash following for oss article sort Permutations II Given a collection of numbers that might contain duplicates,

leetCode 83.Remove Duplicates from Sorted List(刪除排序鏈表的反復) 解題思路方法

排序 back ace 去除 adding 思路 詳細 init ica Given a sorted linked list, delete all duplicates such that each element appear only once.

leetcode 113. Path Sum II (路徑) 解題思路方法

csdn 節點 consola eno == lin sans 要求 又一 Given a binary tree and a sum, find all root-to-leaf paths where each p

leetCode 23. Merge k Sorted Lists (合併k個排序連結串列) 解題思路方法

Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 思路:此題是由合併兩個排序連結串

leetCode 70.Climbing Stairs (爬樓梯) 解題思路方法

Climbing Stairs  You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1 or 2 steps. In how

leetCode 85.Maximal Rectangle (最大矩陣) 解題思路方法

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 思路:此題的意思是給一個為0或1的矩

leetCode 41.First Missing Positive (第一個丟失的正數) 解題思路方法

First Missing Positive  Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, an

leetCode 38.Count and Say (計數發言) 解題思路方法

Count and Say  The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as

leetCode 7. Reverse Integer (數字反轉) 解題思路方法

問題: Reverse Integer  Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 本題需要注意的地方在於數字反轉後有可能溢位,所

leetCode 83.Remove Duplicates from Sorted List(刪除排序連結串列的重複) 解題思路方法

Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1-&

leetCode 24. Swap Nodes in Pairs (雙數交換節點) 解題思路方法

Swap Nodes in Pairs  Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you