【2020.01.24】算法学习记录——字母异位词分组

算法-字母异位词分组


给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:

输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]

来源:力扣(LeetCode)

import java.util.*;
public class GroupAnagram {
    public static void main(String[] args){
        String[] input = new String[6];
        input[0] = "eat";
        input[1] = "tea";
        input[2] = "tan";
        input[3] = "ate";
        input[4] = "nat";
        input[5] = "bat";
        System.out.println(groupAnagrams(input));
    }

    public static String order(String input){
        String result = "";
        char[] str = input.toCharArray();
        for(int i = 1; i<str.length;i++){
            for(int j=0; j<str.length-1;j++){
                if(str[j]>str[i]){
                    char temp = str[i];
                    str[i] = str[j];
                    str[j] = temp;
                }
            }
        }
        result = String.valueOf(str);
        return result;
    }

    public static List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<List<String>>();

        for(int i = 0; i<strs.length; i++){
            String change = order(strs[i]);
            if(result.size() == 0){
                List<String> inner = new ArrayList<String>();
                inner.add(strs[i]);
                result.add(inner);
            }
            else{
                String flag = "not";
                for(int j = 0; j<result.size();j++){
                    if(order(result.get(j).get(0)).equals(change)){
                        result.get(j).add(strs[i]);
                        flag = "have";
                    }
                }
                if(flag.equals("not")){
                        List<String> addition = new ArrayList<>();
                        addition.add(strs[i]);
                        result.add(addition);
                }
            }
            }
        return result;
        }
    }

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