I have a list of following characters of class Token:
3 ( 16 ) 23 ( 24 ( 40 ) 50 ( 66 ) 76 ) 83 ( 88 ( 104 ) 127 )
My requirement is to find the pair of parenthesis within this list. In the list, the pairs of parenthesis are: 3,16; 24,40; 50,66; 23,76; 88,104; 83,127.
I'm trying to do this with following approach:
public static Dictionary<int,int> GetPair(List<Token> data)
{
List<Token> token = data;
var pair = new Dictionary<int, int>();
int startIndex = -1;
int currentPosition = -1;
int finalIndex = -1;
foreach (var item in token)
{
if (item.TokenValue == "(" && (currentPosition == -1 || currentPosition>startIndex) )
{
startIndex = item.TokenID;
currentPosition = startIndex;
}
if (item.TokenValue == ")")
{
finalIndex = item.TokenID;
currentPosition = finalIndex;
pair.Add(startIndex, finalIndex);
}
}
return pair;
}
public class Token
{
public int TokenID { get; set; }
public string TokenValue { get; set; }
}
I'm stuck in finding the position of "23 (" because there is another opening parenthesis in the list and it replaces it with "24 (". Kindly help me to fix the logic here??