Algorithm: prefix matching of English words - hash table

topic

Give you an English word library (array), which contains hundreds of thousands of English words, enter a string, and judge whether it is a prefix of a certain word (or judge whether it is wrong).

common ideas

Traverse the word library and use indexOf to judge the prefix.

The time complexity exceeds O(n), and the calculation amount of indexOf should be considered.

Hash table idea

A hash table is a logical structure that can be implemented in any language, such as:

  • Use Object or Map in js
  • structure in C language
  • HashMap in Java

The hash table is queried by key, and the time complexity is O(1).

const obj = {
    
    
	a: {
    
    
		a: {
    
    

		},
		b: {
    
    
			
		},
		...
	},
	b: {
    
    

	},
	...
}

The time complexity becomes O(m), where m represents the length of the word. But the price is that English words need to be converted into such a hash table. The hash table does not need to be moved frequently, so the problem is not big.

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/130449194