본문 바로가기

algorithm

[LeetCode] 28. Implement strStr()

leetcode.com/problems/implement-strstr/

 

Implement strStr() - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1. Problem

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

 

Example 1:

Input: haystack = "hello", needle = "ll"

Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"

Output: -1

Example 3:

Input: haystack = "", needle = ""

Output: 0

 

Constraints:

  • 0 <= haystack.length, needle.length <= 5 * 104
  • haystack and needle consist of only lower-case English characters.

2. Code

public class ImplementStrStr {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int result = strStr("hello", "lo");
		System.out.println(result);
	}

    public static int strStr(String haystack, String needle) {
    	if(needle.equals(" "))
    		return 0;
        return haystack.indexOf(needle);
    }
}

 

3. Report

 String Class의 indexOf 메소드를 이용해서 문제 해결했다.

 

indexOf의 소스코드는 아래와 같다.

	public int indexOf(int var1, int var2) {
		int var3 = this.value.length;
		if (var2 < 0) {
			var2 = 0;
		} else if (var2 >= var3) {
			return -1;
		}

		if (var1 < 65536) {
			char[] var4 = this.value;

			for (int var5 = var2; var5 < var3; ++var5) {
				if (var4[var5] == var1) {
					return var5;
				}
			}

			return -1;
		} else {
			return this.indexOfSupplementary(var1, var2);
		}
	}

	private int indexOfSupplementary(int var1, int var2) {
		if (Character.isValidCodePoint(var1)) {
			char[] var3 = this.value;
			char var4 = Character.highSurrogate(var1);
			char var5 = Character.lowSurrogate(var1);
			int var6 = var3.length - 1;

			for (int var7 = var2; var7 < var6; ++var7) {
				if (var3[var7] == var4 && var3[var7 + 1] == var5) {
					return var7;
				}
			}
		}

		return -1;
	}

자바의 java.lang라이브러리 jar파일을 디컴파일한 결과 난독화 되어있어서 변수명을 읽기가 어려웠다.

 

'algorithm' 카테고리의 다른 글

[leetCode] 27. Remove Element  (0) 2021.01.22
[leetCode] 57. Insert Interval  (0) 2021.01.18
[LeetCode] 58. Length Of LastWord  (0) 2021.01.14
[LeetCode] 9. Palindrome Number  (0) 2021.01.07
[LeetCode] 7. ReverseInteger  (0) 2021.01.07