2011-08-28 20 views
-1

我有一個List<Data>包含隨機對象:io個字符。如何實現這樣修剪異常數據?

該數據有兩種類型,i和o(Data.type)。

我想用Java編寫一個函數,它可以將列表排列爲i,o,i,o,i,o&hellip ;.

如果遇到幾個i,應該選擇第一個。如果遇到幾個o,它應該選擇最後一個。

有人可以告訴我最簡單的方法來實現它嗎?

+4

您問題不清楚:顯示輸入和輸出,像一個單元測試。 – Bohemian

+1

爲什麼不計算列表中的i和o,然後寫下列表? –

+0

這是功課嗎?如果是這樣,請用'家庭作業'標記。 – Douglas

回答

4

確實沒有,如果你選擇第一個或最後一個字符的結果字符串被desplayed,所以嘗試這種差異[總是需要第一個匹配的字符]:

(*)假設輸入爲通過 'STR'

String str = "ioooioooiooiiiiooo"; 
    StringBuilder sb = new StringBuilder(); 
    Matcher matcher = Pattern.compile("i+|o+").matcher(str); 
    while (matcher.find()) { 
     sb.append(str.charAt(matcher.start())).append(','); 
    } 
    if (sb.length() > 0) { 
     sb.deleteCharAt(sb.length()-1); 
    } 
    System.out.println(sb); 

使用sb.toString()指示的格式從StringBuilder

編輯讓您得到的字符串:
剛剛注意到您的輸入是一個列表,假設它是List<Character>,您可以執行以下操作,當然可以將其更改爲List<AnyOtherObject>

List<Character> result = new LinkedList<Character>(); 
    Iterator<Character> iter = list.iterator(); 
    if (!iter.hasNext()) { /*handle empty list and return*/ } 
    Character last = iter.next(); 
    if (last.charValue() == 'i') { 
     result.add(last); 
    } 
    while (iter.hasNext()) { 
     Character current = iter.next(); 
     if (last.charValue() == current.charValue()) { 
      last = current; //we don't care for i's which i is the last, but we do for o's, so we set it anyway. 
      continue; 
     } else if (current.charValue() == 'i') { 
      result.add(last); 
      result.add(current); 
     } 
     last = current; 
    } 
    if (last.charValue() == 'o') { 
     result.add(last); 
    } 
+0

實際上,有一個區別,因爲那些「我」字符在我們的業務邏輯中是不同的,所以你有什麼建議嗎? – MemoryLeak

+0

更新我的問題,請看看 – MemoryLeak

+0

@MemoryLeak:我編輯了答案的第二部分[處理列表]以匹配您編輯的問題。 – amit

1

如果我看到正確的,你已經定義了一些數據類是這樣的:

public class Data { 
    private char type; 
    private Foo value; // placeholder for whatever else this kind of 
         // object represents 

    public char getType() { 
     return type; 
    } 
    // other methods... 
} 

也有一些List<Data>包含這些 對象的集合。現在您要創建一個新的List<Data>,其中多個Datatype相同的所有 序列將 合併爲單個元素。如果它是Data的一個序列,那麼i, 單個元素應該是該序列的第一個元素,否則它應該是它的最後一個元素。

這將導致如下代碼:

public List<Data> conflateList (List<Data> longList) { 
    List<Data> resultList = new ArrayList<Data>(); 
    for (Data element: longList) { 
     if (element.getType() == 'i' && 
      (resultList.size() == 0 || 
       resultList.get(resultList.size() - 1).getType() == 'o')) { 
      // only the first consecutive `i` is added 
      resultList.add(lastElement); 
     } 
     if (element.getType() == 'o') { 
      if (resultList.size() == 0 || 
       resultList.get(resultList.size() - 1).getType() == 'i') { 
       // all `o`s are at least temporarily added 
       resultList.add(element); 
      } else { 
       // consecutive `o`s are replaced 
       resultList.set(resultList.size() - 1, element); 
      } 
     } 
    } 
    return resultList; 
}