【问题标题】:Getting a chain of letters from a string based on a specific letter根据特定字母从字符串中获取字母链
【发布时间】:2013-06-29 19:23:10
【问题描述】:

我有一个字符串,其中包含表示平面图(VLSI 布局)的波兰符号,它包含类似:“1234VHV56HV”的内容。 (仅供参考,这意味着:垂直分离 3 和 4,然后水平分离结果和 2,然后垂直分离结果和 1,水平分离 5 和 6,然后垂直分离前两个结果。)

假设字符串变量被调用:polishNotation。包含的字母只有 'V' 表示垂直或 'H' 表示水平。

我正在尝试应用一种名为:"Simulated Annealing" 的算法来更改波兰表示法,所以我想随机选择一个索引(当然小于 PolishNotation.Length)和如果这个索引指向一个字母('V'或'H'),我想得到包含它的字母链,然后将每个'V'更改为'H'并将每个'H'更改为'V'.. . 换句话说:补链!

  • 例如:假设 PolishNotation = "1234VHV56HV" 并且随机索引 = 5,所以结果是 "H"...我想检索 "VHV" 并将其补全为:"1234HVH56HV"。
  • 另一个例子:假设 PolishNotation = "1234VHV56HV" 并且随机索引 = 9,所以结果是 "H"...我想检索 "HV" 并将其补全为:"1234VHV56VH"。
  • 另一个例子:假设 PolishNotation = "1234VHV56HV" 并且随机索引 = 6,所以结果是 "V"...我想检索 "VHV" 并将其补全为:"1234HVH56HV"。

我希望我自己清楚...有什么建议吗?我正在使用 C#.net

【问题讨论】:

  • 如果您想在 C# 中获得答案,您可能需要将 C# 添加为标签

标签: c# notation chain letters polish


【解决方案1】:

你可以试试这样的。我敢打赌,有一种方法可以用正则表达式做到这一点,但我不知道。

    string Complement(string floorPlan)
    {
        int index = rand.Next(floorPlan.Length); //get a random integer within array bounds

        if (floorPlan[index] != 'H' || floorPlan[index] != 'V') // if we didn't grab a letter, return
            return floorPlan;

        int start = index; //we'll need to find the start of the 'letter group'

        for (int i = index; i >= 0; i--) // work backwards through the string
            if (floorPlan[i] == 'H' || floorPlan[i] == 'V') // updating if we find another letter
                start = i;
            else // break when we don't
                break;            

        StringBuilder sb = new StringBuilder(floorPlan); // use a string builder for ease of char replacement

        for (int i = start; i < floorPlan.Length; i++) // using the start index, interate through
            if (floorPlan[i] == 'V') // and replace accordingly
                sb[i] = 'H';
            else if (floorPlan[i] == 'H')
                sb[i] = 'V';
            else // breaking when we encounter a number
                break;

        return sb.ToString();
    }

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2018-04-07
    • 2018-07-11
    • 1970-01-01
    相关资源
    最近更新 更多