R, 122 bytes
x=el(strsplit(scan(,""),""));n=seq(x);y=x!="/";for(i in n)cat(rep(" ",diffinv(y[n[-1]-1]+y[n[-1]]-1)[i]),x[i],"\n",sep="")
Try it online! (Note that el(x)
does not work on TIO so I have replaced it with x[[1]]
for one extra byte.)
With extra whitespace:
x = el(strsplit(scan(,""),""))
n = seq(x)
y = x!="/"
for(i in n) {
cat(rep(" ", diffinv(y[n[-1]-1]+y[n[-1]]-1)[i]), x[i], "\n", sep="")
}
Explanation: This answer is based on the observation that the number of leading spaces changes each line by -1, plus the number of /
in the previous and current lines.
If we have N slashes, the variable y
is a vector of length N, with 1 for each position with /
, 0 otherwise. Therefore, to get the change in number of leading spaces per line, we calculate y[1:(N-1)] + y[2:N] - 1
. The function diffinv
converts these differences into a sequence, starting with 0. The rest is just a matter of assembling each line as the required number of trailing spaces, followed by the relevant slash and a newline.