Java [leetcode 30]Substring with Concatenation of All Words

來源:互聯網
上載者:User

標籤:

題目描述:

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 words exactly once and without any intervening characters.

For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

解題思路:

首先設定一個HashMap,裡面索引值為單詞,元素值為對應單詞出現的次數,將其作為比較的模板。

我們首先在一個大的迴圈裡面獲得字串的第一個位置開始的第一個單詞,查看上述的模板Map中是否存在這個單詞。如果不存在,那麼外面的大迴圈直接後移一位,匹配下一個位置開始的單詞。同時內嵌迴圈,用於逐個單詞進行排查。如果尋找是存在的,那麼我們把這個單詞加入到新的Map中,同時統計次數也需要遞增。接下來查看這個新Map中的該單詞出現的次數是否小於的個等於模板中該單詞出現的次數,如果大於該次數,說明情況是不符合要求的,跳出該內層迴圈,外層迴圈的指標後移。

最後如果內層迴圈如果順利走完,則說明從該位置開始所有的單詞都是匹配的,那麼將該位置添加到List中,否則外層迴圈指標指向下一個字元的外置,繼續開始類似的判斷。

代碼如下:

public class Solution {    public List<Integer> findSubstring(String s, String[] words) {List<Integer> list = new ArrayList<Integer>();Map<String, Integer> map = new HashMap<String, Integer>();Map<String, Integer> tmp = new HashMap<String, Integer>();int sLength = s.length();int wordsNum = words.length;int wordsLength = words[0].length();int j;if (sLength < wordsNum || wordsNum == 0)return list;for (int i = 0; i < wordsNum; i++) {if (map.containsKey(words[i]))map.put(words[i], map.get(words[i]) + 1);elsemap.put(words[i], 1);}for (int i = 0; i <= sLength - wordsNum * wordsLength; i++) {tmp.clear();for (j = 0; j < wordsNum; j++) {String word = s.substring(i + j * wordsLength, i + j* wordsLength + wordsLength);if (!map.containsKey(word))break;if (tmp.containsKey(word))tmp.put(word, tmp.get(word) + 1);elsetmp.put(word, 1);if (tmp.get(word) > map.get(word))break;}if (j == wordsNum)list.add(i);}return list;}}

 

Java [leetcode 30]Substring with Concatenation of All Words

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.