题目是这样的:设计一个class,名叫MutableString,实现以下方法:charAt(int i),substring(int start, int end),setCharAt(int i, char c)。要求空间复杂度O(1)。
这是一道看雪论坛的求助面试题。
public class MutableString {
private String str;
public MutableString(String str) {
this.str=str;
}
char charAt(int i)
{
byte[] ff=str.getBytes();
return (char)ff[i];
}
String substring(int start, int end)
{
return new String(str.getBytes(),start-1,end-1);
}
String setCharAt(int i,char c)
{
byte[] ff=str.getBytes();
ff[i-1]=(byte) c;
//str=new String(ff);
return new String(ff);
}
}
测试代码:
public class ggg {
/**
* @param args
*/
public static void main(String[] args) {
String ddd="abcdefghi";
MutableString ff=new MutableString(ddd);
System.out.print(ff.substring(2, 3)+" ");
System.out.print(ff.charAt(3));
System.out.print(" "+ff.setCharAt(3,'l'));
}
}
测试结果:
bc d abldefghi