第一道题,权值250
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.
思想:尝试按照尽量最大字节数写入,这样可以减少写入的次数
public class DiskClusters {
int allSize;
public int minimumFragmentation(String disk, int size){
allSize = size;
return write(disk,size);
}
//写入
private int write(String disk, int size){
int count=0;
if(size!=0){
String str = getWriteStr('.',size);
if(disk.indexOf(str)>=0){//如果成功写入,将写入的地方打上标志
disk = disk.substring(0,disk.indexOf(str)) + getWriteStr('o',size)
+ disk.substring(disk.indexOf(str)+str.length(),disk.length());
//减少剩余写入的字节数
allSize = allSize - size;
if(allSize>0){//如果还有剩余的没有写入,则将剩余的写入
count = count + 1 + write(disk,allSize);
}else{
count = 1;
}
}else{//如果写入不成功,减少写入的字节数
count = count + write(disk,size-1);
}
}
return count;
}
//返回要写入的字符串
private String getWriteStr(char ch,int size){
String str = "";
for(int i=0;i
}
return str;
}
评论