I always say that finding the real complexity is not that simple. Looking over we can say easy that it is O(n) being n
the size of string s
which will be known when typing the text, ie, is linear complexity because it takes the amount of steps to perform equal to the size of s
.
But there is a problem that many people would let escape. When you keep concatenating string, which is immutable by default in C#, there is an additional cost to copy the string current for a new one, so at each step there will still be a cumulative copy cost. So if you change the algorithm and use an object of string Properly initialized changeable can only consider O(n). You can read more on What makes Join() so superior compared to other concatenation techniques?.
And for other reasons it is more efficient to do:
using static System.Console;
using System.Text;
public class Program {
public static void Main() {
WriteLine(" Digite a Palavra");
var s = ReadLine();
var revs = new StringBuilder(s.Length);
for (int i = s.Length - 1; i >= 0; i--) revs.Append(s.Substring(i, 1));
WriteLine(revs);
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
But if you are trying to check a palindrome there is still more efficient way, since you don’t need to make any copies and can check only half of the characters.
You can read more on What is the complexity of an algorithm?.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero