如何在Java中表示一个字符串,以便删除字符串的第一个字符需要O(1)时间?
这个问题:关于字符串字符删除,讨论了在Java中使用子字符串删除字符串的第一个字符。但是,正如Java 7此处所发现的那样,子字符串实现现在以O(字符串的长度)运行。如何使用Java删除O(1)中的第一个字符?
我只是想要一个替代方案,如果可能的话,使用其他类似的类(如StringBuffer,StringBuilder等)来处理字符串和字符。或通过其他任何方式,肯定必须有一种方法可以删除O(1)中单词的第一个字符。
如果String
没有先复制a的字符,就无法获得它们,这需要O(n)的时间,因为它必须横穿整个字符串以进行复制...除非您使用反射。
现在,您要讨论替换字符串中的第一个字母,以及可替换地替换字符串中每个单词的第一个字母。如果要替换每个单词的第一个字母,则必须横切整个字符串,即O(n)时间-别无选择。
如果您只想替换第一个字母,则可以使用反射,但我不建议您实际使用,而是使用.substring(String)
。
您要寻找的方法:
/**
* Replaces the first letter in a {@code String} in O(1) time.
*
* This uses reflection to change the values and will modify the
* {@code String}s values.
*
* @param str the {@code String} to modify.
* @param letter the new first letter of the {@code String}.
* @return {@code str}
*/
public static String replaceFirstLetter(String str, char letter) {
if (str == null) {
throw new NullPointerException("str cannot be null");
}
if (str.length() == 0) {
throw new IllegalArgumentException("String cannot be empty");
}
try {
Field value
= str.getClass().getDeclaredField("value");
value.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(value, value.getModifiers() & ~Modifier.FINAL);
char[] values = (char[]) value.get(str);
values[0] = letter;
value.set(str, values);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
ex.printStackTrace();
//This should never happen
}
return str;
}
请注意,此方法将修改String
您传入的内容,因此这会破坏类的不变规则,因此String
不应在生产代码中使用。同样,与使用此方法相比,仅横向穿过弦可能会更快。
public static void main(String[] args) {
String s = "Hello";
replaceFirstLetter(s, 'Y');
System.out.println(s);
System.out.println(replaceFirstLetter("Hello", 'G'));
}
这很好地证明了这一点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句