Task

A string of characters of a certain length is specified. Determine the new term, obtained after lengthening the initial one for each character met once and turning over. Example: a = ”abac” rez = “ccabba”.

I did everything except the last point. It is necessary that duplicate characters in a line be derived once, without doubling. I don’t know how to do it

import java.util.Scanner; public class MainFive { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Введите строку:"); String str = sc.nextLine(); int ln = str.length(); char[] chars= str.toCharArray(); for (int i=ln-1; i>=0; i--){ System.out.print(chars[i]+""+chars[i]); } } } 

    1 answer 1

    Try this:

      import java.util.Scanner; public class MainFive { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Введите строку:"); String str = sc.nextLine(); int ln = str.length(); char[] chars= str.toCharArray(); ArrayList<Character> characters = new ArrayList<>(); int count = 0; for (int i = 0; i < ln; i++) { for (int j = 0; j < ln; j++) { if (chars[i] == chars[j] && i != j) { count += 1; } } if (count > 0) { characters.add(chars[i]); count = 0; } else { characters.add(chars[i]); characters.add(chars[i]); } } // перевернутый вывод for (int i = characters.size() - 1; i >= 0; i--) { System.out.print(characters.get(i)); } } } 
    • No, I did not understand correctly) Then duplicate characters will simply be removed, and from the string "abzca" you will get "aczba". And you need to get "acczzbba". - Hacker
    • @Hacker Redid - Sergey