Concatenate substrings of all words

Keywords: Java

Given a string s and some words of the same length. Find out the starting position of a substring in s that can be formed by concatenation of all words in words.

Note that the substring should exactly match the words in words, and there should be no other characters in the middle, but the sequence of words in words should not be considered.

 

Example 1:

Input:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
Output: [0,9]
Interpretation:
The substrings starting with indexes 0 and 9 are "barfoor" and "foobar", respectively.
The order of output is not important, and [9,0] is also a valid answer.

Example 2:

Input:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
Output: []
package leetCode_5_14;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/** 
* @author : caoguotao
* @date Creation time: 5:58:13 PM, May 17, 2019 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/
public class Solution30_1 {

	public static void main(String[] args) {
		//"wordgoodgoodgoodbestword"
		//["word","good","best","good"]
		//"foobarfoobar"
		//["foo","bar"]
		String[] words = new String[] {"foo","bar"};
		List<Integer> list =  findSubstring("barfoothefoobarman", words);
		for (Integer integer : list) {
			System.out.println(integer);
		}

	}
	public static List<Integer> findSubstring(String s, String[] words) {	
	    Set<Integer> set = new HashSet<Integer>();
	    if(words.length == 0)
			return new ArrayList<>(set);
	    int m = words.length, n = words[0].length();
	    int cur = 0;
	    while(cur + m * n <= s.length()) {
	    	String[] temp = new String[words.length];
			for(int i = 0; i < words.length; i++) {
				temp[i] = words[i];
			}
			int i1;
			for(i1 = 0; i1 < m; i1++) {
				String curStr = s.substring(cur + n * i1, cur + (n * (i1 + 1)));
				 boolean flag = isIn(temp, curStr);
				 if(flag == false) {
					 break;
				 }
			}
			if(i1 == m) {
				set.add(cur);
			}
			cur++;
	    }
	    return new ArrayList<>(set);
	}
	private static boolean isIn(String[] temp, String curStr) {
		int i;
		for(i = 0; i < temp.length; i++) {
			if(temp[i].equals(curStr)) {
				temp[i] = "";
				break;
			}
		}
		if(i == temp.length) {
			return false;
		}
		return true;	
	}
}

 

Posted by fiona on Fri, 08 Nov 2019 12:35:56 -0800