题目
描述
n
从左到右删除句子中的感叹号。n
是正整数。
例子
remove("Hi!",1) === "Hi"
remove("Hi!",100) === "Hi"
remove("Hi!!!",1) === "Hi!!"
remove("Hi!!!",100) === "Hi"
remove("!Hi",1) === "Hi"
remove("!Hi!",1) === "Hi!"
remove("!Hi!",100) === "Hi"
remove("!!!Hi !!hi!!! !hi",1) === "!!Hi !!hi!!! !hi"
remove("!!!Hi !!hi!!! !hi",3) === "Hi !!hi!!! !hi"
remove("!!!Hi !!hi!!! !hi",5) === "Hi hi!!! !hi"
remove("!!!Hi !!hi!!! !hi",100) === "Hi hi hi"
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD development by writing your own tests
public class SolutionTest {
@Test
public void fixedTests() {
// assertEquals("expected", "actual");
assertEquals("Hi", Kata.remove("Hi!", 1));
assertEquals("Hi", Kata.remove("Hi!", 100));
assertEquals("Hi!!", Kata.remove("Hi!!!", 1));
assertEquals("Hi", Kata.remove("Hi!!!", 100));
assertEquals("Hi", Kata.remove("!Hi", 1));
assertEquals("Hi!", Kata.remove("!Hi!", 1));
assertEquals("Hi", Kata.remove("!Hi!", 100));
assertEquals("!!Hi !!hi!!! !hi", Kata.remove("!!!Hi !!hi!!! !hi", 1));
assertEquals("Hi !!hi!!! !hi", Kata.remove("!!!Hi !!hi!!! !hi", 3));
assertEquals("Hi hi!!! !hi", Kata.remove("!!!Hi !!hi!!! !hi", 5));
assertEquals("Hi hi hi", Kata.remove("!!!Hi !!hi!!! !hi", 100));
}
}
解题
My
public class Kata {
public static String remove(String s, int n){
int length = s.length();
for (int i = 0, count = 0; i < length && count < n; i++) {
if (s.contains("!")) {
s = s.replaceFirst("!", "");
count++;
}
}
return s;
}
}
题目太新,还没啥人做出让人眼前一亮的答案
Other
public class Kata {
public static String remove(String s, int n){
for(int i = 0; i<n;i++)
s = s.replaceFirst("!","");
return s;
}
}
后记
上述答案和我一样用了replaceFirst(),为了简单未考虑n过大的情况,不算最佳实践。
网友评论