标签:
Substring with Concatenation of All Words
问题:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in wordsexactly once and without any intervening characters.
思路:
Hashtable + string API
我的代码:
import java.util.Hashtable; public class Solution { public List<Integer> findSubstring(String s, String[] words) { List<Integer> rst = new ArrayList<Integer>(); if(s==null || s.length()==0 || words==null || words.length==0) return rst; int wordLen = words[0].length(); int count = words.length; Hashtable<String,Integer> ht = new Hashtable<String,Integer>(); for(String word: words) { if(ht.containsKey(word)) ht.put(word, ht.get(word)+1); else ht.put(word,1); } for(int i=0; i<=s.length()-count*wordLen; i++) { String sub = s.substring(i,i+count*wordLen); if(isValid(sub, ht, i, wordLen)) rst.add(i); } return rst; } public boolean isValid(String sub, Hashtable<String,Integer> ht, int start, int wordLen) { Hashtable<String,Integer> found = new Hashtable<String,Integer>(); for(int i=0; i<=sub.length()-wordLen; i+=wordLen) { String key = sub.substring(i,i+wordLen); if(ht.containsKey(key)) { if(found.containsKey(key)) { found.put(key,found.get(key)+1); if(found.get(key) > ht.get(key)) return false; } else found.put(key,1); } else return false; } return true; } }
学习之处:
Substring with Concatenation of All Words
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4490536.html