How to find the last repeated character in a string with Java

2 Answers

0 votes
public class Program {
    static int get_last_character_repeated(String s) { 
        int len = s.length(), ch_idx = -1;
           
        for (int i = 0; i < len; i++) { 
            for (int j = i + 1; j < len; j++) { 
                if (s.charAt(i) == s.charAt(j)) { 
                    ch_idx = i;
                    break;
                } 
            }
        } 
        return ch_idx; 
    }     
    public static void main(String args[]) {
        String s = "abcdxypcbadom"; 
         
        int i = get_last_character_repeated(s); 
        
        if (i == -1) 
            System.out.println("Not found"); 
        else
            System.out.println(s.charAt(i)); 
    }
}
 
 
/*
run:
 
d
 
*/

 



answered Jan 25, 2020 by avibootz
edited Nov 1 by avibootz
0 votes
public final class StringUtils {

    /**
     * Finds the last repeated character in a string.
     *
     * Examples:
     * "abca"          -> 'a'
     * "abcbd"         -> 'b'
     * "abcde"         -> '\0' (not found)
     * "abcdxypcbop"   -> 'p'
     * "abcdxypcbadom" -> 'd'
     *
     * Time Complexity: O(n)
     * Space Complexity: O(1)
     *
     * @param str the input string
     * @return the last repeated character, or '\0' if none exists
     */
    public static char findLastRepeatedCharacter(String str) {
        if (str == null || str.isEmpty()) {
            return '\0';
        }

        // Frequency table for ASCII characters.
        int[] frequency = new int[256];

        // Count occurrences of each character.
        for (int i = 0; i < str.length(); i++) {
            frequency[str.charAt(i)]++;
        }

        // Traverse from right to left.
        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);

            if (frequency[ch] > 1) {
                return ch;
            }
        }

        // No repeated character found.
        return '\0';
    }

    public static void main(String[] args) {

        System.out.println(findLastRepeatedCharacter("abca"));          
        System.out.println(findLastRepeatedCharacter("abcbd"));         

        char result = findLastRepeatedCharacter("abcde");
        System.out.println(result == '\0' ? ' ' : result);             

        System.out.println(findLastRepeatedCharacter("abcdxypcbop"));   
        System.out.println(findLastRepeatedCharacter("abcdxypcbadom")); 
    }
}
 
 
/*
run:
 
a
b
 
p
d
 
*/

 



answered Nov 1 by avibootz
...