leetcode438 find all the letters in the string word ectopic

Brief introduction

In fact, my algorithm is not the strong point, then today do 438 this question when I found a very admirable idea, record it here and share with you:
First, look at the title:
Given a string s and a non-empty string p, find all s is a substring of the letter p ectopic word, which returns the substring starting index.

String contains only lowercase letters, and the character string length p and s is not more than 20,100.

Description:

Ectopic word letters refer to the same letters, but arranged in different strings.
The order of the answers that were not considered.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/find-all-anagrams-in-a-string
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

My thoughts

Let me talk about my ideas (not over time, not interested can skip directly to see the god of solution)

  • With the number of each word stored hashMap of p
    * left <- 0 right <- 0 about which the sliding window is marked
    * list res result list
    * the while (right <s.len) {
    * IF (marker == 0 ) {// marker used to mark now there are several not find
    * res.append (left)
    * charAt (left) ++ value of the HashMap;
    * restoration marker
    * the else {}
    * right ++;
    * the Check HashMap (charAt (right)) is less than 0, {
    * traversing left ++ left = right until the CH; update left. Continue
    * the else {}
    * hashMap '-;
    * IF hashMap' == 0 the respective bitmap position 0
    *}
    *}
    *}

Code:

public List<Integer> findAnagrams1(String s, String p) {
        Map<Integer, Integer> charMap = new HashMap<Integer, Integer>();
        Map<Integer, Integer> bitMap = new HashMap<Integer, Integer>();
        List<Integer> res = new ArrayList<Integer>();
        int marker = 0;
        int left = 0, right = -1;
        for (int i = 0; i < p.length(); i++) {
            int ch = p.charAt(i);
            if (charMap.containsKey(ch)) {
                charMap.put(ch, charMap.get(ch) + 1);
            } else {
                charMap.put(ch, 1);
            }
        }
        bitMap.putAll(charMap);
        int marker_=p.length();
        marker = p.length();

        while (right < s.length()) {
            if (marker == 0) {
                res.add(left);
                left = left + 1;
                right = left - 1;
                marker = marker_;
                charMap.clear();
                charMap.putAll(bitMap);
//                int mark = s.charAt(left);
//                charMap.put(mark, charMap.get(mark) - 1);
//                marker++;
            } else {
                if (right + 1 < s.length()) {
                    right++;
                }else{
                    break;
                }
                if (!charMap.containsKey(Integer.valueOf(s.charAt(right)))) {
                    left = right + 1;
                    marker = marker_;
                    charMap.clear();
                    charMap.putAll(bitMap);
                } else {
                    if (charMap.get(Integer.valueOf(s.charAt(right))) == 0) {
                        while (left <= right) {
                            int tmp = s.charAt(left);
                            if (tmp == Integer.valueOf(s.charAt(right))) {
                                left++;
                                break;
                            } else {
                                charMap.put(tmp, charMap.get(tmp) + 1);
                                marker++;
                                left++;
                            }
                        }
                    } else {
                        int tmp = s.charAt(right);
                        charMap.put(tmp, charMap.get(tmp) - 1);
                        marker--;
                    }
                }
            }
        }
        return res;
    }

In fact, I was writing when he felt a little jumbled and cumbersome, of course, I usually will take the time to optimize it, but also because the more anxious, directly see the solution of the great God, let me on her own and learning for a long time.

Okami solution

Directly on the code:

public List<Integer> findAnagrams(String s, String p) {
        int slength = s.length();
        int plength = p.length();
        int conter = 0;
        StringBuilder sb = new StringBuilder(p);
        List<Integer> result = new ArrayList();
        for(int i=0; i<slength; i++)
        {
            if(sb.indexOf(Character.toString(s.charAt(i))) != -1)
            {
                conter++;
                sb.delete(sb.indexOf(Character.toString(s.charAt(i))), sb.indexOf(Character.toString(s.charAt(i)))+1);
            }
            else
            {
                if(p.indexOf(Character.toString(s.charAt(i))) != -1)
                {
                    conter--;
                    i--;
                    sb.append(s.charAt(i-conter));
                }
                else
                {
                    conter = 0;
                    sb =  new StringBuilder(p);
                }
            }


            if(conter == plength)
            {
                result.add(i-plength+1);
                conter--;
                sb.append(s.charAt(i-plength+1));
            }
        }
        return result;
    }

In fact, here it is not the idea, then I study a little, here to do some summary.

First of all, I have to say, that I caught the disintegration of the fixed sliding window routine which, of course, for some topics, the sliding window is very efficient, but it should not only know the sliding window to limit their ideas.

  • Declarations of variables:

Authors declare
int = slength s.length ();
int pLength = p.length ();
int Conter = 0;
the StringBuilder SB = new new StringBuilder§;
List the Result = new new ArrayList ();

Needless to say the first two, are the length. Conter is then recorded to the current scan has several characters of the string belonging to p. P is the current sb is to record what has been found in s character, find a'll delete it from sb, then the rest is yet to match.
result is to record the results.

  • Process logic
for ch in str.s {
	if ch in sb:   sb.delete(ch)  同时conter计数+1
	else(也就是说不在sb串中的ch){
		首先判断在不在p中
		if 在p中: 将ch的索引i回退,conter--,(i-conter)元素增加到sb。
		//这里其实我也困惑了一会,后来发现这里才是精彩的地方,当面对这种情况的时候,
		//其实是已经找到了足够数量的某个字母char0,但是又遇到了一个char0,这个字母现在多了,
		//那么怎么样才能继续走下去呢,就需要将前面的已经遇到的第一个char0找到,从index(char0)+1开始,
		//重新计算。所以这里就是首先将i--,表示重新扫描,并且将conter--,用i-conter来找到当前
		//的最左面的第一个字母charLeft,增加到sb,就是说又需要这个charLeft了。
		else (也不在p中) 说明这个字母肯定不对了,只能舍弃重新开始扫描。 所以初始化变量 :conter=0 sb = (p)

		if conter == plength:
			符合条件,记录res;
	}
}

to sum up

  • Use StringBuilder, str avoid the use of an adder.
  • Implicit sliding window sliding window method is the real essence, you do not necessarily need to move alternately left and right, the heart is the advanced algorithms window.

Encourage each other ~

Published 51 original articles · won praise 55 · views 8957

Guess you like

Origin blog.csdn.net/qq_40742298/article/details/104576390