Substring with Concatenation of All Words

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;

    }

}
View Code

 

学习之处:

  • String[] words可以包含重复的word,此处不适宜用Hashtable了,之前在微软的在线笔试中碰到了相应的问题,忘记考虑可以包含重复的元素了,丢了一些分数。
  • 既然包含重复的元素,怎么用hashtable进行存储呢,value解决方法有两个,一个是用List标记每一个重复的元素,另外一个使用count表明有几个重复的元素,第一种方式太过于复杂了,采用第二种方法,通过两个hashtable比较次数,判断是否由相应的word
  • 这道题是竟然暴力解法也能解决,注意命名规范
  • 改变不好的习惯 坏习惯+1

你可能感兴趣的:(substring)