2013-07-02 96 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