简体   繁体   中英

Difference between first index and last index of the char in the given string

I have a String Unitedin . Here the char "n" is occurred at index 1 and index 6; The Difference between index number is 5 Similarly for "i" which occurs at index 2 and index 5. The Difference is 3.

I need to Print the chars according to ascending order of there Difference at the OutPut.

Challenge is I cannot use any type of array list or List or hashMap or set or linked hash etc

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    StringBuilder temp = new StringBuilder();
    StringBuilder output = new StringBuilder();
    System.out.println("Enter a string : ");
    String instring = in.next();
    for (int i = 0; i < instring.length(); i++) {
        for (int j = i + 1; j < instring.length(); j++) {
            if (instring.charAt(i) == instring.charAt(j)) {
                temp.append(instring.charAt(i));
            }
        }
    }

    for (int m = 0; m < temp.length(); m++) {
        for (int p = m + 1; p < temp.length(); p++) {
            if (m == temp.length() - 1) {
                output.append(temp.charAt(m));
            } else if (instring.lastIndexOf(temp.charAt(m), 0) >= instring.lastIndexOf(temp.charAt(p), 0)) {
                output.append(temp.charAt(p));
            } else {
                output.append(temp.charAt(m));
            }
        }
    }
    System.out.println(output);
}

I am Getting output as i . Can anyone help me? Expected output = in

Smth. like that. This is not the best performance, but it does not use Collections :

public static String foo(String str) {
    str = str.toLowerCase();

    int[] letters = new int[26];
    Arrays.fill(letters, Integer.MIN_VALUE);

    for (int i = 0; i < str.length(); i++)
        if (letters[str.charAt(i) - 'a'] == Integer.MIN_VALUE)
            letters[str.charAt(i) - 'a'] = -i;

    for (int i = str.length() - 1; i >= 0; i--)
        if (letters[str.charAt(i) - 'a'] != Integer.MIN_VALUE)
            letters[str.charAt(i) - 'a'] += i;

    return IntStream.range(0, letters.length)
                    .filter(i -> letters[i] > 0)
                    .boxed()
                    .sorted(Comparator.comparingInt(i -> letters[i]))
                    .map(i -> String.valueOf((char)('a' + i)))
                    .collect(Collectors.joining());
}

In case you do not want to use Streams , then the second part it:

int cur = 1;
boolean checkNext;
StringBuilder buf = new StringBuilder();

do {
    checkNext = false;

    for (int i = 0; i < letters.length; i++) {
        if (letters[i] < cur)
            continue;

        checkNext = true;

        if (letters[i] == cur)
            buf.append((char)('a' + i));
    }

    cur++;
} while (checkNext);

return buf.toString();

import java.util.TreeMap;
import java.util.Scanner;

public class SameCharOccurenceDiff {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int firstIndex = 0;
        int lastIndex = 0;
        TreeMap<Integer,Character> outputMap = new TreeMap<Integer,Character>();
        String stringInput = sc.next();
        StringBuilder strBuilder = new StringBuilder(); 
        sc.close();
        for (int i = 0; i < stringInput.length(); i++) {
            char chr = stringInput.charAt(i);
            firstIndex = stringInput.indexOf(chr);
            lastIndex = stringInput.lastIndexOf(chr);
            int diff = lastIndex-firstIndex; 
            if( diff > 0) {
                outputMap.put(diff,chr);
            }
        }
        for (char c : outputMap.values()) {
            strBuilder.append(c);
        }
        System.out.println(strBuilder);
    }
}

Edit: ( Without using TreeMap )

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class SameCharOccurenceDiff {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int firstIndex = 0;
        int lastIndex = 0;
        int count = 0;
        String stringInput = sc.next().toLowerCase();
        String[] stringInputArr = new String[stringInput.length()];
        StringBuilder strBuilder = new StringBuilder(); 
        sc.close();
        for (int i = 0; i < stringInput.length(); i++) {
            char chr = stringInput.charAt(i);
            firstIndex = stringInput.indexOf(chr);
            lastIndex = stringInput.lastIndexOf(chr);
            int diff = lastIndex - firstIndex; 
            if( diff > 0 && !inArray(stringInputArr,diff+""+chr)) {
                stringInputArr[count] = diff+""+chr;
                count++;
            }
        }
        //System.out.println(Arrays.toString(stringInputArr));
        Arrays.sort(stringInputArr,0,count,new Comparator<String>() {
            public int compare(String s1, String s2) {
                int num1 = Integer.parseInt(s1.replaceAll("[^\\d]", ""));
                int num2 = Integer.parseInt(s2.replaceAll("[^\\d]", ""));
                return num1 - num2;
            }
        });
        //System.out.println(Arrays.toString(stringInputArr));
        for (String str : stringInputArr) {
            if(str == null)break;
            strBuilder.append(str.replaceAll("\\d", ""));
        }
        System.out.println(strBuilder);
    }
    public static boolean inArray(String[] arr,String chr) {
        boolean isPresent = false;
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] == null)break;
            if(arr[i].equalsIgnoreCase(chr)) {
                isPresent = true;
                break;
            }
        }
        return isPresent;
    }
}

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