Question

I m confused when the strings have more than 2 common letters: "abc" + "bcd" = "abcd" , no repetitions like "abccd" or "abbccd"

public static String make_new_name(String name1, String name2) {
    String result = "";
    for (int i = 0 ; i < name1.length() ; i++) {
        System.out.println("=========== i " + name1.charAt(i) + " =================");
        for (int j = 0 ; j < name2.length() ; j++) {
            System.out.println(" j : " + name2.charAt(j)); 
            if (name1.charAt(i) != name2.charAt(j)) {
                result += name1.charAt(i);
            } else {
                result += name1.charAt(j);
            }
        }
    }
    System.out.println(result) ;
    return result ;
}   

but this code does not work! Please help.

No correct solution

OTHER TIPS

Assuming that this is a learning exercise, I wouldn't spoil your fun by writing your code.

Here is a simple algorithm that needs only one explicit loop: go through all suffixes of the first string, and check if they represent a prefix of the second string. Start with the longest suffix (which is the entire first wors) and continu with the shorter and shorter ones. Once you located a suffix that matches the prefix of the second word, remove that suffix, and append the second string to the result.

In Java you get a suffix of a word by calling substring with one parameter. To check if a string is a prefix of another string, use startsWith method.

You can set difference the two strings and then concat them to get the result.

 public static String make_new_name(String name1, String name2) {
     Set<Character> nameSet1 = new HashSet<Character>();
     for(char c : name1.toCharArray())
     {
         nameSet1.add(c);
     }

     Set<Character> nameSet2 = new HashSet<Character>();
     for(char c : name2.toCharArray())
     {
         nameSet2.add(c);
     }

     nameSet1.removeAll(nameSet2); // Set Difference

     StringBuilder sb = new StringBuilder(nameSet1.size() + nameSet2.size());

     for(Character c : nameSet1)
     {
         sb.append(c);
     }
     for(Character c : nameSet2)
     {
         sb.append(c);
     }

     return sb.toString();

 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top