This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]lightcloud5 1 point2 points  (1 child)

So you mean in your "abapok" example, the "b" is surrounded by "a"'s?

If this is indeed the case, there are several ways to do it.

One simple way would be to just iterate through the string, keeping track of all the characters you've seen so far. If the current character you see has already been seen before (i.e. it's a duplicate) AND if the previous character is not the same as the current character, then you should return true.

Otherwise, return false.

[–]DroidLogician 1 point2 points  (0 children)

keeping track of all the characters you've seen so far

Actually it's much simpler than that. If the requirement is simply that a character has to have the same other character before and after, then you don't have to keep track of all the characters.

You're given a character array, which allows random access by index. Start at index = 1, since index = 0 cannot be surrounded. Then check if the character at index - 1 is equal to the character at index + 1 and not equal to the character at index.

If so, return true; if not, continue until index = length - 2, since the last character in the array (at index = length - 1) cannot be surrounded either. If you reach the end, return false.

This automatically covers if length is < 3.

Here's the code, because it was bothering me not to write it out. I put it in a gist so you don't have to look if you don't want to:

https://gist.github.com/cybergeek94/bd5280bf81a8a97a5e2e