这是我的代码:
public static String repeat(String s, int n) {
String res = "";
for (int i = 0; i < n; i++) {
res += s;
}
return res;
}
public static void main(String[] args) {
String word = "mathematics";
int n = word.length()/2;
for (int i = 0; i <= n; i++) {
System.out.print(repeat(" ", n- i));
System.out.println(word.substring(n -1, n + i + 1)); //here is the problem I think
}
}
或者你知道一些更好的解决方案吗?感谢
答案 0 :(得分:2)
子字符串的起始索引是n-1
,它是常量,但必须更改,必须n-i
减少到单词的开头
for (int i = 0; i <= n; i++) {
System.out.print(repeat(" ", n- i));
System.out.println(word.substring(n -i, n + i + 1));
}
m
ema
hemat
themati
athematic
mathematics