2013-10-05 55 views
0

在這個問題中,我將編寫一個方法,它接受stringsArrayListinteger。在這種情況下,該整數將按照整數所指示的次數重複單個單詞。例如,如果列表在調用方法前存儲值["how", "are", "you?"],並且k爲4,則應存儲值["how", "how", "how", "how", "are", "are", "are", "are", "you?", "you?", "you?", "you?"]如果k爲0或否定,則在調用後該列表應該爲空。在一個數組中重複序列

public static void stutter(ArrayList<String> thing, int k) { 
    if (k <= 0) { 
     thing.clear(); // if k is 0 
     return; 
    } 

    for (int i = 0; i< thing.size(); i+= k) { 
     String temp = thing.get(i); 
     for (int j = 0; j < k; j++) { 
      thing.add(temp); 
     } 
    } 
} 
+0

那麼你面臨的問題是什麼? – dharam

+0

我把它運用起來,沒關係。 –

回答

0

我沒有測試它請覈實

public static void stutter(ArrayList<String> thing, int k) { 
    if (k <= 0) { 
     thing.clear(); // if k is 0 
     return; 
    } 

    ArrayList<String> newList = new ArrayList<>(); 
    for (int i = 0; i< thing.size(); i++) { 
     String temp = thing.get(i); 
     for (int j = 0; j < k; j++) { 
      newList.add(temp); 
     } 
    } 
    thing.clear(); 
    thing.addAll(newList); 
} 
0

沒關係,我解決了它;只是一些重新安排和它的工作。

0

沒關係,我解決了這個問題;只是一些重新安排和它的工作。

public static void stutter(ArrayList<String> thing, int k) { 
    if (k <= 0) { 
     thing.clear(); 
     return; 
    } 
    for (int i = 0; i< thing.size(); i+= k) { 
     String temp = thing.get(i); 
     for (int j = 1; j < k; j++) { 
      thing.add(i, thing.get(i)); 
     } 

     if (i == thing.size()) { 
      return; 
     } 
    } 
} 

如果你們可以在此找到任何漏洞,隨時指出它們。

+0

解決方案的時間複雜度將大於O(K * thing.size()) –

相關問題