简体   繁体   中英

How do you check if the characters in a string are grouped together?

I want to be able to check if the characters in a string are grouped together.

The definition of being grouped: Not repeated somewhere else other than its cluster. In "AABBBBACDDD" it is not grouped since the last "A" is not in its cluster (first set of A's).

The characters do not have to be in alphabetical order.

For example:

AAABBBBBCCC → is grouped

AABBBBACDDD → is not grouped


There is definitely a loop involved but I don't know the conditions to check if it is group or not

This sounds like an algorithms question more than C++. So the algorithm is going to be like this, (pseudo-code). You can write C++ code for this (I can help you if you want):

function is_grouped(str):
  seen_letters = {} # set of seen letters so far
  last_letter = None
  for c in str:
    if last_letter == c:  # if it is the same letter as before continue
      continue
    if last_letter != c && c in seen_letters:  # seen before and a new cluster
      return false
    seen_letters.add(c) # new unsee cluster
    last_letter = c
  return true

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