简体   繁体   中英

What's wrong with this return?

I'm new to not using a main method and i started leet coding in java and they give you the boilerplate code in a particular format. my logic is fine, but for some reason im not returning the proper string. can you guys help me on this one?

class Solution {
    public String defangIPaddr(String address) {
        char[] newChar = new char[address.length()];
        address.getChars(0, address.length(), newChar, 0);

        for(int i = 0; i < address.length();i++) {
            if(newChar[i] == '.') {
                return "[.]";
            }else
                return Character.toString(newChar[i]);
        }
    }
}

For a given input 1.1.1.1 I want as output 1[.]1[.]1[.]1 .

Based on the clarification in comments, instead of trying to replace each dot separately, use String#replaceAll method to replace them all at once.

String address = "1.1.1.1";
address = address.replaceAll("\\.", "[.]"); //replace all dots
System.out.println(address); //prints 1[.]1[.]1[.]1

If you insist of doing the replacement yourself though, instead of messing with a bunch of indices, simply try to recreate the string from the start, appending each character to a StringBuilder , but if it is a dot append [.]

String address = "1.1.1.1";
StringBuilder sb = new StringBuilder();
for (char c : address.toCharArray()) {
    if (c == '.')
        sb.append("[.]");
    else
        sb.append(c);
}
address = sb.toString();
System.out.println(address); //prints 1[.]1[.]1[.]1

The logic is not good because it seems like you are returning the first character of the input string only. You can use a string builder for your solution or just a new string you will appending to. Sample:

class Solution {
    public String defangIPaddr(String address) {
        char[] newChar = new char[address.length()];
        address.getChars(0, address.length(), newChar, 0);

        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < address.length();i++) {
            if(newChar[i] == '.') {
                sb.append("[.]"); //append to the string builder
            }else
                sb.append(Character.toString(newChar[i]));
        }

        return sb.toString(); //return the string then
    }
}

I hope this may help. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM