Untitled

mail@pastecode.io avatar
unknown
java
a year ago
2.7 kB
13
Indexable
Never
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Solution {
    class entry{
        int position;
        char value;
        int level;
        entry(char value, int level, int position)
        {
            this.value = value;
            this.level = level;
            this.position = position;
        }
    }

    String helper(entry[] e, ArrayList<entry> list){
        String result = "";
        Comparator<entry> comparator = Comparator.comparing(entry -> entry.level);
        comparator = comparator.thenComparing(entry -> entry.position);

        Stream<entry> entryStream = list.stream().sorted(comparator);

        List<entry> sortedEntries = entryStream.collect(Collectors.toList());

        for(entry entry : sortedEntries){
            result += entry.value;
        }
        return result;
    }

    public String convert(String s, int numRows) {
        ArrayList<entry> lol = new ArrayList<>();
        //first go down number of rows
        //then go up diagonally number of rows
        //then go down number of rows
        //then go up dia
        int length = s.length();
        int num_of_chars = 0;
        String direction = "DOWN";
        int previous_move = 0;
        int rowCounter = 0;
        entry[] entries = new entry[length];
        while(num_of_chars < length){
            entries[num_of_chars] = new entry(s.charAt(num_of_chars), rowCounter, num_of_chars);
            System.out.println(s.charAt(num_of_chars) + " " + rowCounter + " " + num_of_chars);
            if(rowCounter == numRows-1 && direction == "DOWN" && previous_move == 0 || rowCounter == 0 && direction == "DIAGONAL" && previous_move == 1){
                if(direction == "DOWN"){
                    direction = "DIAGONAL";
                }
                else{
                    direction = "DOWN";
                }
            }
            if(direction == "DOWN"){
                rowCounter = rowCounter + 1;
                previous_move = 0;
            }
            else{
                rowCounter = rowCounter - 1;
                previous_move = 1;
            }
            num_of_chars++;
        }
        for(entry e :entries){
         lol.add(e);
        }
        if(numRows == 1){
            return s;
        }
        else{
        return helper(entries,lol);
        }
    }

    public static void main(String[] args){
        String s = "PAYPALISHIRING";
        int n = 4;
        Solution sol = new Solution();
        System.out.println(sol.convert(s,4));
    }
}