简体   繁体   中英

How to find the shortest consecutive substring which contains certain characters in a string in python?

I have a high school competition in coding tomorrow, and while practicing I found many problems where this is asked from me.

Specifically, in this certain task, you have a string which contains numbers that can range from 1 to K . Let's say K is 4, the string could be 1234 , 1222231 , 124123143 , 1311233114 , or anything like that.

I am asked to find the length of the shortest consecutive substring which contains all the values from 1 to K . If such a substring doesn't exist, I am supposed to return -1 .

In case I didn't explain clear enough, if the string was 1234 , the shortest substring would be 1234 and its length is 4. If it was 1222231 , there isn't a number 4 in there, so it should return -1 . In 124123143 the shortest length is also 4 ( 4123 , 2314 ), and in the case it was 1311233114 , the shortest length would be 6 - 233114 .

What would be the best (or easiest) way to find this out?

For k=4 you can do something like this

(?=([1234])(?!\1)([1234])(?!\1|\2)([1234])(?!\1|\2|\3)([1234]))

See demo.

https://regex101.com/r/uN5aG9/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM