0

How can I find distinct repetitive character in string using Java.

For the string 4567895443577

Here, the first distinct repetitive character is 5

Ip:n:1 output:4
   n=2     op=5
   n=3     op=7
   n=4     op=doest exist
constantlearner
  • 5,157
  • 7
  • 42
  • 64
  • This might help you - http://stackoverflow.com/questions/664194/how-can-i-find-repeated-characters-with-a-regex-in-java – linead Jul 27 '11 at 07:43
  • 1
    I don't understand... 4 is repeated first, as in "44" or as in it's the first character that appears twice? If the latter, it isn't, 5 is. –  Jul 27 '11 at 07:46
  • @constantlearner: what should ("112233",3) return? 3 or null? what should ("4554",1) return? 4 or 5? – amit Jul 27 '11 at 08:10
  • this question actually sounds like a homework –  Jul 27 '11 at 08:41

5 Answers5

2

create HashSet and HashMap: set,map and int count=0, iterate over the string, and add each character and its index. at the end - each character's value will be the LAST index.
iterate over the String again, and check if the index is as appears in the map. if it does (or the character appears in the set) - ignore it.
if a character is not in the set, and index as is and as in map don't match - increase count (until it reaches n).

complexity: O(n)

public static Character findN(String str,int n) { 
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    int len = str.length();
    for (int i=0;i<len;i++) { 
        map.put(str.charAt(i),i);
    }
    int count=0;
    HashSet<Character> set = new HashSet<Character>();
    for (int i=0;i<len;i++) {
        if (set.contains(str.charAt(i))) continue;
        if (map.get(str.charAt(i)) != i) {
            count++;
            if (count == n) return str.charAt(i);
            set.add(str.charAt(i));
        }
    }
    return null; //it does not exist

}
amit
  • 175,853
  • 27
  • 231
  • 333
2

This should work:

public static char findChar(String s, int length) {
int[] counts = new int[10];

// iterate over the letters and increment the count
int stringLength = s.length();
for(int i = 0; i < stringLength; i++ ) {
    char c = s.charAt(i);
    int value = Character.getNumericValue(c);
    counts[value]++;
}

int counter = 0; // how many chars repeated so far
for(int i = 0; i < stringLength; i++ ) {
    char c = s.charAt(i);
    int value = Character.getNumericValue(c);
    if(counts[value] >= 2) {

    counts[value] = -1; // do not count this twice
    counter++;

    if(counter == length) {
        return c;
    }
    }
}
return '\u0000'; // null char
}
Caner
  • 57,267
  • 35
  • 174
  • 180
  • what will findChar("4554",2) return? it supposes to return '4'. also I believe findChar("112233,3") will return null, while it is supposed to return '3'. – amit Jul 27 '11 at 08:02
  • ("4554",2) should return 5 since '5' is the first number that shows up twice. ("112233",3) should return null since there is no number that exist 3 times in the string. – Caner Jul 27 '11 at 08:05
  • also, a tip: never `put i – amit Jul 27 '11 at 08:06
  • one of us got it wrong. I believe the OP wants to return the nth character that repeats more then once. – amit Jul 27 '11 at 08:09
  • @amit then in the example given by the asker the answer for `n=2` should be `4` – Caner Jul 27 '11 at 08:12
  • no, because 4 appears before 5, as in his example, (s,1)=4 and not 5. – amit Jul 27 '11 at 08:13
  • Hi for input 2 its 2nd repetative character not number of times its repeated.Thanks – constantlearner Jul 27 '11 at 08:27
  • @constantlearner ok I got it, and fixed my code, check it out – Caner Jul 27 '11 at 08:38
0
 /* 
 * Ex-OR basic : 0^0 = 0, 0^1 = 1, 1^0 = 1, 1^1 = 0  
 * 
  Ex-ORing bits of all characters in String nums = "4567895443577"
  i   Operation                Bitwise operation    Result(bin)   Result(Dec)  
  0       4 ^ 5 ...arr[0]^arr[1]       100 ^ 101            001             1                 
  //NOTE : first occurence as result = 1 should be skipped
  ----------------------------------------------------------------------------      
       Result(i-1)        arr[i]
  for:  
  1       1        ^        5          001 ^ 101            100             4
  2       4        ^        6          100 ^ 110            010             2
  3       2        ^        7          010 ^ 111            101             5
  4       5        ^        8          0101 ^ 1000         1101            13
  5      13        ^        9          1101 ^ 1001         0100             4
  6       5        ^        4          0101 ^ 0100         0001             1                  
 // break "for" found repeated element. return 5           
 * */
public class RepeatedNumber {
 public static void main(String args[]) {
    String nums = "4567895443577";
    char  repeated = (char) findRepeated(nums.toCharArray()) ;
    System.out.println("result ="+repeated);
 }
 public static int findRepeated(char arr[]) {

    int result = arr[0]^arr[1];
    int repeated = arr[0];
    //find out number repeated more than once in array
    if(result != 0) {
        for(int i = 1; i < arr.length; i++) {

            result = result ^ arr[i];

            if(result == 1 || arr[i] == arr[i-1]) {

                repeated = arr[i];
                break;
            }
        }
    }
    return repeated;
 }
}
0

You should create a HashSet which implements Set Interface.

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
0

This can be done by the following code.

I have used HashMap keys as an input characters and value as a counter.

String str = "4567895443577";
char[] chars = str.toCharArray();
HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
for( char c : chars )
{
    if( charMap.containsKey( c ) ){
        charMap.put(c, charMap.get(c) + 1 );
    }else{
        charMap.put(c, 1);
    }
}
for( Entry<Character, Integer> entry : charMap.entrySet() )
{
    System.out.println( "Character '"+entry.getKey()+"' is repeated for '"+entry.getValue()+"' times." );
}
Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49