本题为微软公司 Microsoft Corporation (应该是在印度招聘所用的)面试题。难度不大,但不容易做对。下面来分析一下。
Problem
Given two strings, one is a text string and the other is a pattern string. The task is to print the indexes of all the occurrences of pattern string in the text string. For printing, starting index of a string should be taken as 1. The strings will only contain lowercase English alphabets (‘a’ to ‘z’).
Examples
Example 1:
Text string: birthdayboy
Pattern string: birth
Output: [1]
Example 2:
Text string: geeksforgeeks
Pattern string: geek
Output: [1, 9]
Complexity Constraints
Expected Time Complexity: O (|text| + |pattern|)
Expected Auxiliary Space: O (1)
Parameter Constraints
1 <= |text| <= 5 * 10 ^ 5
1 <= |pattern| <= |text|
Answer (in Java)
/* By Li Yi Chen on 2024/3/6, in BALI Indonesia */
import java.util.Scanner;
public class Search_Pattern
{
public static void main (String [] args)
{
// Initialize the strings
String text = "";
String pattern = "";
// Read the strings
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter text string: ");
text = scanner.nextLine();
System.out.println("Please enter pattern string: ");
pattern = scanner.nextLine();
// Double-check
System.out.println("The text string you entered is: " + text);
System.out.println("Length of text string: " + text.length());
System.out.println("The pattern string you entered is: " + pattern);
System.out.println("Length of pattern string: " + pattern.length());
int pattern_len = pattern.length();
int ptr = 0;
int index = 0;
System.out.println("The required index array is: ");
// Core code
while (true)
{
String new_string = text.substring(ptr); // Cut the string from point ptr
index = new_string.indexOf(pattern);
// Does not contain
if (index == -1)
{
break;
}
System.out.print((index + ptr + 1) + " ");
ptr = index + pattern_len;
// Out of bound
if (ptr > new_string.length() - pattern_len)
{
break;
}
}
}
}
运行示例
示例1:
text字符串和pattern字符串相同:
示例2:
text字符串仅包含1个pattern字符串:
示例3:
text字符串包含多个pattern字符串:
示例4:
不包含的情况(text仍比pattern长):
此时程序进入第1次循环就break掉了,故没有任何输出。
思路简述
本题的解题思路亦可以说十分直观且多样,笔者这里采用的(短时间内第一个想到的方法,并不一定是时间复杂度最优的)是递归地使用字符串对象的indexOf()方法,不断地缩短字符串,直至穷尽所有可能的解。思维量虽然并不大,但想要在短时间内正确无误地写出无bug的程序,并不是十分容易。