当前位置:   article > 正文

[LeetCode] Substring with Concatenation of All Words_you are given a string, s, and a list of words, l,

you are given a string, s, and a list of words, l, that are all of the same

Substring with Concatenation of All Words

 

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

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

这两天为了准备WAP的面试正好在练习JAVA,于是重写了这道题,发现JAVA果然好简洁。
思路就不说了,还是那个滑动窗口。
  1. public class Solution {
  2. public ArrayList<Integer> findSubstring(String S, String[] L) {
  3. // Start typing your Java solution below
  4. // DO NOT write main() function
  5. ArrayList<Integer> ret=new ArrayList<Integer>();
  6. if ( S==null || L==null || L.length==0 )
  7. return ret;
  8. HashMap<String,Integer> words=new HashMap<String,Integer>();
  9. // HashMap<String,Integer> need =new HashMap<String,Integer>();
  10. for(int i=0;i<L.length;i++){
  11. if ( words.containsKey(L[i]) ){
  12. int t = words.get(L[i]);
  13. words.put(L[i], t+1);
  14. //need.put(L[i], t+1);
  15. }else{
  16. words.put(L[i],1);
  17. // need.put(L[i],1);
  18. }
  19. }
  20. int wordLength=L[0].length();
  21. for(int i=0;i<wordLength;i++){
  22. HashMap<String,Integer> need =new HashMap<String,Integer>(words);
  23. int start=i,end=i;
  24. int needCnt=L.length;
  25. if ( (S.length()-start)< (wordLength*needCnt))
  26. break;
  27. for(;end<S.length();end+=wordLength){
  28. if ( S.length()-end < wordLength )
  29. break;
  30. String tmp= S.substring(end,end+wordLength);
  31. if (words.containsKey(tmp)){
  32. int t=need.get(tmp);
  33. need.put(tmp,t-1);
  34. if ( t>0)
  35. needCnt--;
  36. }
  37. if ( needCnt==0 ){
  38. while(true){
  39. String toRemove=S.substring(start,start+wordLength);
  40. if (words.containsKey(toRemove) ){
  41. int t =need.get(toRemove);
  42. if ( t <0 ){
  43. need.put(toRemove,t+1);
  44. }
  45. else
  46. break;
  47. }
  48. start+=wordLength;
  49. }
  50. if (end-start == wordLength*(L.length-1))
  51. ret.add(start);
  52. }
  53. }
  54. }
  55. return ret;
  56. }
  57. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/252609
推荐阅读
相关标签
  

闽ICP备14008679号