All Leetcode questions don't seem to have main methods, I wonder how I could run the code in a local IDE(say, eclipse)? For instance, I was trying to run this one:
Q: Write a method/function to replace all the space in String s to " ".
The code:
public class ReplaceSpace {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(Character c : s.toCharArray()) {
if(c == ' ')
res.append(" ");
else
res.append(c);
}
return res.toString();
}// that'll work in the Leetcode editor
public static void main(String[] args) {
String s = "We are happy.";
System.out.print(s.replaceSpace); //reports "cannot be resolved to a type" error
}
}
Also, if anyone could explain a little why Leetcode editor could run code without the main method it would be great.
CodePudding user response:
To test the code in your local IDE, simply provide your own main. The pre-written code usually contains non-static methods. This gives you two ways to test your code.
Add static
public class ReplaceSpace
{
public static String replaceSpace(String s)
{
...
}
public static void main(String[] args)
{
System.out.println (replaceSpace("We are happy"));
}
}
Create object
public class ReplaceSpace
{
public String replaceSpace(String s)
{
...
}
public static void main(String[] args)
{
ReplaceSpace rs = new ReplaceSpace();
System.out.println (rs.replaceSpace("We are happy"));
}
}
CodePudding user response:
replaceSpace is a method of ReplaceSpace class and not String class. String is the return type for replaceSpace method. You're trying to call the replaceSpace method on the String class object.
In order to run the code, you need to instantiate an object of ReplaceSpace class and then call the replaceSpace method on its object by passing the string which you want to replace as a parameter. Like so:
public static void main(String[] args) {
ReplaceSpace rs = new ReplaceSpace();
String replacedString = rs.replaceSpace("We are happy.");
System.out.println(replacedString);
}
Another way is to make the replaceSpace method static and call the method without an object instantiation.
As to how Leetcode runs the code behind the scenes, they don't need to use main methods to run your code. They just have unit tests written for your function with exhaustive test cases to test your solution rather than running your code via main methods.
