Java-O(n)-faster


  • 1
    R
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    public class Solution {
        public String convert(String text, int nRows) {
            if(nRows==1){
                return text;
            }
            Map<Integer, StringBuilder> result = new HashMap<>(nRows);
            int eachRoundNumber = nRows + (nRows/*deduct the turing number*/-1)/*deduct its self*/-1;
            // in order to calculate it easier, use the nature order, and when get the char from the string, make a n-1
    
            // saving time from the loop below
            for(int i=1; i<=nRows;i++){
                result.put(i,new StringBuilder());
            }
    
            for(int i=1; i<=text.length();i++){
                // if the key equal or less the nRow number, means it in the go down path, else, means in its going up path
                // when going down, we just get the number from mold, when going up, it should get from the end
                int key = i%eachRoundNumber;
                key=key==0?key+eachRoundNumber:key;
                key = key <=nRows?key:nRows-(key%nRows);
                // the index should be i-1
    //            if(!result.containsKey(key)){
    //                result.put(key,new StringBuilder());
    //                result.get(key).append(text.charAt(i-1));
    //            }
    //            else {
                    result.get(key).append(text.charAt(i-1));
    //            }
            }
            StringBuilder rest = new StringBuilder();
            for(int i=1; i<=nRows;i++){
                rest.append(result.get(i));
            }
            return rest.toString();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.