My accepted java code for ZigZag Conversion


  • 0
    P

    I use a asc sign to traverse the array.

    public class Solution {
    	public String convert(String s, int nRows) {
    		if("".equals(s)||nRows==1){
    			return s;
    		}
    		StringBuilder[] sbs=new StringBuilder[nRows];
    		for(int i=0;i<sbs.length;i++){
    			sbs[i]=new StringBuilder();
    		}
    		char[] chars=s.toCharArray();
    		int index=0;
    		boolean asc=true;
    		for(int i=0;i<chars.length;i++){
    			sbs[index].append(chars[i]);
    			if(asc){
    				index++;
    				if(index==nRows){
    					index-=2;
    					asc=false;
    				}
    			}else{
    				index--;
    				if(index==-1){
    					index+=2;
    					asc=true;
    				}
    			}
    		}
    		StringBuilder result=new StringBuilder();
    		for(int i=0;i<sbs.length;i++){
    			result.append(sbs[i]);
    		}
    		return result.toString();
    	}
    }

Log in to reply
 

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