2013-07-02 95 views
2

我有一个字符串,其中包含代表平面布置(VLSI布局)的波兰语表示法,它包含诸如“1234VHV56HV”之类的字符。 (仅供参考,这意味着:单独的3 & 4竖直地然后分离结果& 2水平则结果& 1垂直,独立分离5 & 6水平,那么前面的两个结果垂直分开。)根据特定字母从字符串获取字母链

假设字符串变量称为:波兰语标注。包含的字母仅为'V'(垂直)或'H'(水平)。

我试图应用一种算法:“模拟退火”要更改波兰语表示法,所以我想随机选择一个索引(当然小于polishNotation.Length),如果此索引点到一个字母('V'或'H'),我想得到包含它的字母链,然后将每个'V'改变为'H'并将每个'H'改变为'V'...换句话说:补充链条!

  • 例如:假定波兰表示法=“1234VHV56HV”及随机指数= 5,那么结果是“H” ......我想找回“VHV”和补充它变成:“1234HVH56HV”。
  • 另一个例子:假设polishNotation =“1234VHV56HV”,随机索引= 9,所以结果是“H”...我想检索“HV”并补充它成为:“1234VHV56VH”。
  • 另一个例子:假设polishNotation =“1234VHV56HV”,随机指数= 6,所以结果是“V”...我想检索“VHV”并补充它成为:“1234HVH56HV”。

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

+0

如果你想在C#中的答案,你可能要添加C#作为标记 – doctorlove

回答

0

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

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(); 
    } 
+0

谢谢您的回复... –

+0

如果现在还不清楚,让我知道。 – Michael