Problem Statement
You are given a String disk representing the clusters on a disk. An 'X'
represents a used cluster, and a '.' represents an available cluster.
You are also given an int size representing the size, in clusters, of a
file waiting to be written to disk. A file can only be stored in
clusters not already being used.
Return the minimum number of groups of consecutive clusters needed to
store the file on the disk. (The disk does not wrap around at the end.)
Return -1 if the disk does not have enough space available to store the
file.
給你一個標有簇的磁碟,X表示已近被使用,.表示可以使用的空間,再給你一個要寫入的位元組數,寫入到未使用的空間中,如果空間不夠返回-1
如果寫入成功返回寫入的次數,如果未使用的空間是連續的只算寫入一次,寫入的方式有很多,求出最少的次數
Definition
Class:
DiskClusters
Method:
minimumFragmentation
Parameters:
String, int
Returns:
int
Method signature:
int minimumFragmentation(String disk, int size)
(be sure your method is public)
類DiskClusters方法public int minimumFragmentation(String disk, int
size)
Constraints
-
disk will contain between 1 and 50 characters, inclusive.
-
Each character of disk will be 'X' or '.'.
-
size will be between 1 and 50, inclusive.
Examples
0)
"."
2
Returns: -1
We can't fit the file on the disk.
1)
".XXXXXXXX.XXXXXX.XX.X.X."
6
Returns: 6
There is only ever one cluster together, so all six clusters are
separated.
2)
"XX..XX....X.XX........X...X.XX...XXXX..XX...XXXXX."
12
Returns: 2
We fit eight clusters together, and four clusters together.
寫入到....和........中,寫入的次數最少只要兩次
3)
".X.XXXX.......XX....X.....X............XX.X.....X."
20
Returns: 3
寫入到.......和.....,............中,寫入的次數最少只要3次
4)
"....X...X..X"
11
Returns: -1
沒有空間返回-1
This problem statement is the exclusive and proprietary property of
TopCoder, Inc. Any unauthorized use or reproduction of this information
without the prior written consent of TopCoder, Inc. is strictly
prohibited. (c)2003, TopCoder, Inc. All rights reserved.
思想:嘗試按照盡量最大位元組數寫入,這樣可以減少寫入的次數
1 public class DiskClusters { 2 int allSize; 3 public int minimumFragmentation(String disk, int size){ 4 allSize = size; 5 return write(disk,size); 6 } 7 //寫入 8 private int write(String disk, int size){ 9 int count=0; 10 if(size!=0){ 11 String str = getWriteStr('.',size); 12 if(disk.indexOf(str)>=0){//如果成功寫入,將寫入的地方打上標誌 13 disk = disk.substring(0,disk.indexOf(str)) + getWriteStr('o',size) 14 + disk.substring(disk.indexOf(str)+str.length(),disk.length()); 15 //減少剩餘寫入的位元組數 16 allSize = allSize - size; 17 if(allSize>0){//如果還有剩餘的沒有寫入,則將剩餘的寫入 18 count = count + 1 + write(disk,allSize); 19 }else{ 20 count = 1; 21 } 22 }else{//如果寫入不成功,減少寫入的位元組數 23 count = count + write(disk,size-1); 24 } 25 } 26 return count; 27 } 28 //返回要寫入的字串 29 private String getWriteStr(char ch,int size){ 30 String str = ""; 31 for(int i=0;i<size;i++){ 32 str = str + ch; 33 } 34 return str; 35 } 36 37 38 39 }