Concise JAVA solution


  • 0
    Solution 1: 
    public String convert(String s, int numRows) {
            if(numRows==1) return s;
            StringBuilder sb=new StringBuilder();
            for(int r=0;r<numRows;r++)
            {
                int delta=2*r;
                for(int i=r;i<s.length();)
                {
                    if(delta!=0||i==0) sb.append(s.charAt(i));
                    delta=(2*numRows-2)-delta;
                    i+=delta;
                }
            }
            return sb.toString();
        }
    

    ========================================================================

    Solution2:
        public String convert(String s, int numRows) {
            if(numRows==1) return s;
            char[] ans=new char[s.length()];
            int index=0;
            int is=0;
            for(int i=1;i<=numRows;i++)
            {
                is=i-1;
                for(;is<ans.length;)
                {
                    if(i!=numRows)
                    {
                        ans[index++]=s.charAt(is);
                        is=is+(numRows-i+1)*2-2;
                    }
                    if(is>=ans.length) break;
                    if(i!=1)
                    {
                        ans[index++]=s.charAt(is);
                        is=is+i*2-2;
                    }
                }
            }
            return new String(ans);
        }

Log in to reply
 

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