论坛首页 综合技术论坛

给大家出道题,算法的

浏览 33058 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (17)
作者 正文
   发表时间:2012-02-21  
package snippet;

import java.util.HashSet;
import java.util.Set;

public class Snippet
{
    public static void main(String[] args)
    {
        String[] strs = { "hat", "top", "potter", "pot", "pier", "ripe" };
        printGroupsWithSameLetters(strs);
    }
   
    public static void printGroupsWithSameLetters(String[] words)
    {
        Set<?>[] sets = new HashSet[words.length];
       
        for (int i = 0; i < words.length; i++)
        {
            Set<Character> set = new HashSet<Character>();
            char[] wordChars = words[i].toCharArray();
            for (char ch : wordChars)
            {
                set.add(ch);
            }
            sets[i] = set;
        }
        for (int i = 0; i < words.length; i++)
        {
            Set<?> set0 = sets[i];
            if (set0 != null)
            {
                System.out.print(words[i]);
                for (int j = i + 1; j < words.length; j++)
                {
                    if (equalWithSameWord(set0, sets[j]))
                    {
                        System.out.print("," + words[j]);
                        sets[j] = null;
                    }
                   
                }
                System.out.println();
            }
        }
    }
   
    public static boolean equalWithSameWord(Set<?> word1, Set<?> word2)
    {
        if (word1 == null || word2 == null)
        {
            return false;
        }
        return (word1.size() == word2.size()) && (word1.containsAll(word2));
    }
}
0 请登录后投票
   发表时间:2012-03-01   最后修改:2012-03-01
		String str="hat,top,potter,pot,pier,ripe"; 
		String[] arr=str.split(",");
		for (int l=arr.length,i=0; i<l; i++)
		{
			if (arr[i]==null) continue;
			System.err.print(arr[i]+" ");
			for (int j=i+1; j<l; j++)
			{
				if (arr[j]==null) continue;
				if (arr[j].replaceAll("["+arr[i].replaceAll("(.)","\\|$1").substring(1)+"]{"+arr[i].length()+"}", "").equals("")) 
				{
					System.err.print(arr[j]+" ");
					arr[j] = null;
				}
			}
			System.err.println();
		}
0 请登录后投票
   发表时间:2012-03-12  
真的是某公司的
0 请登录后投票
   发表时间:2012-03-13  
public class CharComp 
{

	/**
	 * 
	 * 1.给单词排序
	 * 2.给排序后的单词设定标识符
	 * 3.通过标识符在map中查找对应的list,并将其追加其中(未排序的单词)
	 * 
	 */
	
	public static Map<String,Set<String>> getGroupWords(String [] words)
	{
		Map<String,Set<String>> map = new HashMap<String,Set<String>>();
		for(String word:words)
		{
			String id = getID(word);
			Set<String> set = map.get(id);
			if(set==null)
			{
				set =new TreeSet<String>();
				map.put(id, set);
			}
			set.add(word);
		}
		
		return map;
	}
	
	private static String getID(String word)
	{
		char array []= 	word.toCharArray();
		String id="";
		Arrays.sort(array);
		int count = 0;
		char last ='.';
		for(char ch:array)
		{
			if(last == ch||count==0)
			{
				count++;
				last = ch;
			}else
			{
				id = id+last+count;
				count = 1;
				last = ch;
			}
			
			
		}
		if(!".".equals(last))
			id = id+last+count;
		return id;
	}
	
//	public static void main(String args[])
//	{
//		System.out.println(getID("mygodmygod"));
//	}
}

0 请登录后投票
   发表时间:2012-03-16  
基本思路: 将单词排序,便于归并 建立HashMap(String,ArrayList),单词转换为字符数组,排序后,再转为字符串,作为key, 根据可以查找HashMap ,若找到,取value(ArrayList型),将单词或单词序号加入 若没有找到,新建立ArrayList型容器,将单词或单词序号加入,再将key,ArrayList put入HashMap 输出: 遍历HashMap ,即可输出结果 对一般应用,应该足矣,对于大型应用,可能要考虑效率和空间问题 [code="java"]import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; public class SortTest { public HashMap proc(String[] words){ HashMap hmOutput = new HashMap(); for (int i = 0; i 0) System.out.print(","); System.out.print(item); } System.out.println(""); } } public static void main(String[] args) { String[] input = new String[]{"hat", "top", "potter", "pot", "pier", "ripe"}; SortTest st = new SortTest(); st.printGroupsWithSameLetters(input); } }[/code] 输出: hat potter pier,ripe top,pot
0 请登录后投票
   发表时间:2012-03-16  
WIN7,IE8下可视化编辑怎么编辑不了,排版完全乱了,是浏览器的原因,还是没有权限编辑自己的贴子, 谁知道?
0 请登录后投票
   发表时间:2012-05-04  
我是个新手,过来学学,但是我连题都没有看懂(英语不会)。·············
0 请登录后投票
   发表时间:2012-07-04   最后修改:2012-07-04
所有算法的本质都是计算每个字符串对应的一个key(含有相同个数字母的字符串对应的key相同),然后根据key来做对应字符串的分组

我的思路是 用一个charArr[26]数组生成的字符串来表示key,字符串中每出现某个字符,假设为 'c',则charArr['c'-'a']++ , 这样保证了相同类型的字符串对应的key是相同的

至于怎么存储key和对应的一行字符串,我使用 Map<String, List<String>>, charArr[26]可以转化为String

具体代码如下:

//假设数组元素非null非空字符串,假设只考虑小写字母
private static Map<String, List<String>> PrintGroupsWithSameLetters(String[] input) {
	char a = 'a';
	Map<String, List<String>> map = new HashMap<String, List<String>>();
	//遍历输入的字符串数组
	for (String str : input) {
		char[] char26 = new char[26];
		//遍历字符串中的每个字符
		char[] charArray = str.toCharArray();
		for (char c : charArray) {
			//某个字符出现一次则, 用该字符减去'a'后的值作为char26数组索引
			//对应数组元素增加1
			char26[c - a]++;
		}
		String key = new String(char26);//题目要求的同一行的字符串对应的key相同
		if(map.get(key) == null){
			map.put(key, new ArrayList<String>());
		}
		map.get(key).add(str);
	}
	return map;
}
0 请登录后投票
   发表时间:2012-07-06   最后修改:2012-07-06

定义了一个数组。
String words[] = { "der", "hat", "potter", "pot", "pier", "ripe", "tpo", "opt", "red", "blue" };
已经实现了,打印结果如下:
der,red
hat
potter
pot,tpo,opt
pier,ripe
package com.interest;

import java.util.ArrayList;
import java.util.List;

public class Test{
	public static void main(String[] args) {
		String words[] = { "der", "hat", "potter", "pot", "pier", "ripe", "tpo", "opt", "red", "blue" };
		printGroupsWithSameLetters(words);
	}

	public static void printGroupsWithSameLetters(String[] words) {
		int size = words.length;
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < size; i++) {
			list.add(words[i]);
		}

		List<String> newList = new ArrayList<String>();

		for (int i = 0; i < list.size(); i++) {
			String addWord = "";
			for (int j = 1; j < list.size(); j++) {
				if (wordEquals(list.get(0), list.get(j))) {
					addWord += list.get(j) + ",";
				} else {

				}
			}

			addWord = (list.get(0) + "," + addWord);
			list.remove(list.get(0));
			newList.add(addWord.substring(0, addWord.length() - 1));
		}

		for (String string : newList) {
			System.out.println(string);
		}

	}

	public static Boolean wordEquals(String word1, String word2) {
		if (word1.length() != word2.length()) {
			return false;
		}

		int size = word2.length();
		for (int i = 0; i < size; i++) {
			if ((word1.indexOf(word2.substring(i, i + 1)) == -1)) {
				return false;
			}
		}
		return true;
	}
}
0 请登录后投票
   发表时间:2012-09-03  
此题有个强化版本,额外加下面的条件:
待处理的单词链表非常大,不足以存入内存。
0 请登录后投票
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics