catsnow9
BAN USERI solved it using HashMap<String, Integer> where hasmap value contains the max index on that character.
Like in this case the HashMap results in {d=4, b=6, c=7, a=2} ..
In second iteration I just compare the index of the current char and hashmap value if index value is equal that hasmap value just put it in the finalList.
package algo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Lexicographical {
public static void main(String args[]) {
String input = "cbacdcbc";
String[] arr = getArrayFromString(input);
Lexicographical lx = new Lexicographical();
lx.parseList(arr);
}
public void parseList(String[] list) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
int index = 0;
for (String i : list) {
if (map.containsKey(i)) {
if (map.get(i) < index) {
map.put(i, index);
}
}else{
map.put(i, index);
}
index++;
}
index = 0;
List<String> finalList = new ArrayList<String>();
for (String i : list) {
if (index >= map.get(i)) {
finalList.add(i);
}
index++;
}
print(finalList);
}
public void print(List<String> list) {
for (String k : list) {
System.out.print(k + " ");
}
}
public static String[] getArrayFromString(String str) {
String[] arr = null;
if (str != null && str.length() > 0) {
arr = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
arr[i] = str.substring(i, i + 1);
}
}
return arr;
}
}
package algo;
import java.util.ArrayList;
import java.util.List;
public class FindCommonSortedList {
public FindCommonSortedList() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr1 = { 2, 5, 5, 7, 7};
int[] arr2 = { 2, 2, 3, 5, 5, 7 };
FindCommonSortedList fc = new FindCommonSortedList();
fc.findCommon(arr1, arr2);
}
public void findCommon(int[] arr1, int[] arr2) {
List<Integer> arr1List = new ArrayList<Integer>();
for (int i : arr1) {
arr1List.add(i);
}
List<Integer> commonList = new ArrayList<Integer>();
for (int j : arr2) {
if (arr1List.contains(j)) {
commonList.add(j);
int index = arr1List.indexOf(j);
arr1List.remove(index);
}
}
print(commonList);
}
public void print(List<Integer> list){
for (int k : list) {
System.out.print(k + " ");
}
}
}
- catsnow9 September 16, 2015