find a location

Topic description

For a given string, find out the repeated characters and give their positions, such as: abcaaAB12ab12 Output: a, 1; a, 4; a, 5; a, 10, b, 2; b, 11, 1, 8; 1, 12, 2, 9; 2, 13.

Enter description:

The input consists of a string of letters and numbers up to 100 in length.

Output description:

There may be multiple sets of test data, for each set of data,
The positions of the characters are marked according to the format of the sample output.

1. The subscript starts from 0.
2. The same letter in a row indicates where it has appeared.
Example 1

enter

abcaaAB12ab12

output

a:0,a:3,a:4,a:9
b:1,b:10
1:7,1:11
2:8,2:12


The solution to this problem is to build a mechanism similar to the adjacency list. For each character, an adjacency list is established. Each edge node stores position information and vertex table elements. The vertex table node stores the number of edges and whether they have been output.

When outputting, scan the vertex table, if the number of edges is greater than 2 and has not been output, then traverse the information of the output edge, and set the changed vertex as output;


Code:

#include <iostream>
#include <string>
using namespace std;

class posNode
{
public:
    char origin;
    int pos;
    posNode *next;

    posNode(char aOrigin , int aPos)
    {
        origin = aOrigin;
        pos = aPos;
        next = NULL;
    }
};

class charNode
{
public:
    int count;
    posNode *next;
    bool flag;
    charNode()
    {
        count = 0;
        next = NULL;
        flag = true;
    }

};

intmain()
{
    string a;
    int i;
    charNode * p = new charNode [128];
    while(cin>>a)
    {
        for(i=0;i<a.size();i++)
        {
            posNode *q = p[ a[i] ].next;
            if(q == NULL)
            {
                p[ a[i] ].next = new posNode(a[i],i);
            }
            else
            {
                while(q->next != NULL)
                    q=q->next;
                posNode *newNode = new posNode(a[i],i);
                q->next = newNode;
            }
            p[ int(a[i]) ].count ++;
        }

        for(i=0;i<a.size();i++)
        {
            if( p[a[i]].count >=2 && p[a[i]].flag)
            {
                int flag = 0;
                p[a[i]].flag = false;
                posNode *q = p[a[i]].next;
                while(q!= NULL)
                {
                    if(flag)
                        cout<<",";
                    else
                        flag = 1;
                    cout<<q->origin<<":"<<q->pos;
                    q= q->next;
                }
                cout<<endl;
            }
        }
    }
        return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324548569&siteId=291194637