谷歌面试题(2)
来源:互联网 发布:java的职业规划 编辑:程序博客网 时间:2024/05/16 17:56
原题:
// Given a set of words (without duplicates), find all word squares you can build from them.// A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).// For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically.// b a l l// a r e a// l e a d// l a d y// Note: // There are at least 1 and at most 1000 words. // All words will have the exact same length. // Word length is at least 1 and at most 5. // Each word contains only lowercase English alphabet a-z.
答案:
public class Solution { public List<List<String>> wordSquares(String[] words) { List<List<String>> ret = new ArrayList<List<String>>(); if(words.length==0 || words[0].length()==0) return ret; Map<String, Set<String>> map = new HashMap<>(); int squareLen = words[0].length(); // create all prefix for(int i=0;i<words.length;i++){ for(int j=-1;j<words[0].length();j++){ if(!map.containsKey(words[i].substring(0, j+1))) map.put(words[i].substring(0, j+1), new HashSet<String>()); map.get(words[i].substring(0, j+1)).add(words[i]); } } helper(ret, new ArrayList<String>(), 0, squareLen, map); return ret; } public void helper(List<List<String>> ret, List<String> cur, int matched, int total, Map<String, Set<String>> map){ if(matched == total) {ret.add(new ArrayList<String>(cur));return;} // build search string StringBuilder sb = new StringBuilder(); for(int i=0;i<=matched-1;i++) sb.append(cur.get(i).charAt(matched)); // bachtracking Set<String> cand = map.get(sb.toString()); if(cand==null) return; for(String str:cand){ cur.add(str); helper(ret, cur, matched+1, total, map); cur.remove(cur.size()-1); } }}
阅读全文
0 0
- 谷歌面试题(2)
- 谷歌面试题(3)
- 谷歌面试题(4)
- 谷歌面试题(5)
- 谷歌面试题(6)
- 谷歌面试题(7)
- 谷歌面试题(8)
- 谷歌面试题(9)
- 面试题(2)
- 面试题(2)
- 面试题(2)
- 面试题(2)
- 面试题(2)
- 经典试题(2)
- 笔试和面试题(2)---海量数据面试题整理
- java面试题(2)-集合相关面试题
- jsp面试题(2)
- .net面试题(2)
- 谷歌面试题(一)
- httpclient使用实例
- Docker学习系列(一):windows下安装docker
- 3.1.11生产者消费者(n:n)
- C++笔记——动态内存分配
- 谷歌面试题(2)
- JSP学习笔记
- R_等高图
- 2017-10-15离线赛
- 简单筛法判断两整数间的素数
- updateByPrimaryKey和updateByPrimaryKeySelective insert和insertSelective
- App安全增强——我来帮你写C++
- Android Studio若干问题
- Git和Github简单教程