之字形转换

时间:2015-10-02 21:02:24

标签: java data-structures

问题是:字符串“PAYPALISHIRING”在给定行数上以Z字形图案写入,如下所示:(您可能希望以固定字体显示此图案以提高清晰度)

P   A   H   N
A P L S I I G
Y   I   R

然后逐行阅读:“PAHNAPLSIIGYIR”

我已经写了下面的代码,看起来它工作正常,但我可能会错过一些角落案例。你能帮我找一下这个问题的所有角落案例吗?

public static String zigZagConversion(String s , int rowNum){

    if (s == null){
        throw new IllegalArgumentException();
    }
    if (rowNum == 1){
        return s;
    }
    StringBuilder str = new StringBuilder();

    int step = 2 * rowNum - 2 ;

    for (int i = 0 ; i < rowNum ; i++){

        if( i == 0 || i == rowNum -1){

            for (int j = i ; j < s.length() ; j +=step){

                str.append(s.charAt(j));                    
            }               
        }

        else{

            int step2 = 2* (rowNum - i - 1);
            int step3 = step - step2;
            int k = i;
            boolean flag = true;

            while (k < s.length()){
                str.append(s.charAt(k));

                if(flag){                       
                    k += step2;
                    flag = false;
                }
                else{                       
                    k +=step3;
                   flag = false;
                }

            }               

        }
    }
return str.toString();      
}

6 个答案:

答案 0 :(得分:1)

它为"PAYPALISHIRING", 4

提供了错误的输出
P     I    N
A   L S  I G
Y A   H R
P     I

所以正确的答案应该是PINALSIGYAHRPI

但是你的程序会PINALIGYAIHRNPI: &#34; S&#34;缺少一个额外的&#34;我&#34;和一个额外的&#34; N&#34;。

您的修订版本仍然不正确,它提供了PINALSIIGYAHNPI

问题出在中间的while循环中。 你需要交替步数, 设置flag开启和关闭。 你的错误只是将其关闭一次,而不再重新开启。

str.append(s.charAt(k));
if (flag) {
    k += step2;
    flag = false;
} else {
    k += step3;
    flag = true;
}

通过此更正,我相信您的解决方案是正确的。 (我还在那里添加了一个小改进,从if-else分支中提取公共str.append(s.charAt(k));

答案 1 :(得分:0)

从Java的leetcode转换之字形

解决方案

const zigzag = (str, num) => {
  if (num === 1) {
    return str;
  }
  let check = true;
  let result = [];
  let i = 0;
  while (i < str.length) {
    result.push([]);
    let j = 0;
    while (j < num) {
      if (check){
        result[result.length-1].push(str[i]);
        i++;
      } else {
        if (j == 0) {
          result[result.length-1].push(null);
        } else if (j === num-1) {
          result[result.length-1].unshift(null);
        } else {
          result[result.length-1].unshift(str[i]);
          i++;
        }
      }
      j++;
    }
    check = !check;
  }
  let zigzag = [];
  for (let k = 0; k < num; k++){
    for(let l = 0; l < result.length; l++) {
      zigzag.push(result[l][k]);
    }
  }
  return zigzag.join("");
}

示例输入

zigzag("ABCD", 3)

输出

ABDC

运行

https://repl.it/@VinitKhandelwal/zigzag-conversion-javascript

答案 2 :(得分:0)

使用HashMap

    public Boolean SaveDataInDatabase(ResearchBL model, string userID, 
    HttpPostedFileBase ResearchFile, ref string Err)
            {
                var result = false;

                    using (ZUNew1Entities2 db = new ZUNew1Entities2())
                    {
                        if (model.ResearchID > 0)
                        {

                            if (!string.IsNullOrEmpty(model.ResearcherName)
                            && !string.IsNullOrEmpty(model.ResearchName)
                            && !string.IsNullOrEmpty(model.NameJournal)
                            && !string.IsNullOrEmpty(model.ResearchContents)
                            && !string.IsNullOrEmpty(model.VolumeNumber)

                            )
                            {
                                Research research = 
    db.Researches.SingleOrDefault(x => x.IsDeleted == false && x.ResearchID 
    == 
    model.ResearchID);

                                research.ResearchName = model.ResearchName;
                                research.ResearcherName = 
    model.ResearcherName;
                                research.NameJournal = model.NameJournal;
                                research.VolumeNumber = model.VolumeNumber;
                                research.ResearchContents = 
    model.ResearchContents;

                                string day = "01";
                                string cal = model.DateOfPublication + "-" + 
    day;

                                research.DateOfPublication = 
    Convert.ToDateTime(cal);


                                // Update Research File 
    ****************************

                                string File;

                                string uploadFile = 
    "~/UploadFile/Researcher/Files/";

                                if (model.ResearchFile != null)
                                {

                                    var fileName = 
    Path.GetFileName(ResearchFile.FileName);
                                    string pathURL = uploadFile + userID + 
    "_" + DateTime.Now.Hour.ToString() + "_" + 
    DateTime.Now.Minute.ToString() + 
    "_" + DateTime.Now.Second.ToString() + 
    DateTime.Now.Millisecond.ToString() + 
    ".pdf";

                                    var path = 
    Path.Combine(System.Web.HttpContext.Current.Server.MapPath(pathURL));
                                    ResearchFile.SaveAs(path);


                                }
                                else
                                {

                                    research.ResearchFile = null;

                                }


                                db.Entry(research).State = 
                EntityState.Modified;
                                db.SaveChanges();
                                result = true;
                                Err = "";
                                return true;

                            }
                            else
                            {

                                Err = "Fill Boxes !!";
                                return false;

                            }

                        }
                        else
                        {

                            Err = "";
                            result = false;
                            return false;

                        }
                    }

            }

答案 3 :(得分:0)

我在leetcode论坛上的解决方案: https://leetcode.com/problems/zigzag-conversion/discuss/549451/Java-Solution-O(n)-with-algorithm

之字形的数学算法是:

  • originalDiff = numRows * 2-2;
  • 如果->'currRow'等于第一行或最后一行
    • 使用originalDiff(numRows * 2-2)
  • 其他->
    • 对于每个新行:
      • upperDiff + = 2
      • lowerDiff-= 2

示例:

numRows =2 -> originalDiff = 2
PYAIHRN
APLSIIG

3 -> 4
P   A   H   N
A P L S I I G
Y   I   R

numRows = 4 -> originalDiff = 6
P    I    N
A  L S  I G
Y A  H R
P    I 

numRows = 5 -> originalDiff = 8
P    H   
A   SI   
Y  I R 
P L  I G  
A    N
*/

我的解决方案:


class Solution {
    public String convert(String s, int numRows) {
        if(numRows == 1) {
            return s;
        }

        String newString = "";
        int originalDiff = numRows * 2 - 2;
        int diff = originalDiff;
        int upperDiff = 0;

        boolean isGoingDown = true;

        int currIndex = 0;
        int currRow = 0;
        int startingIndex = 0;

        for(int i = 0; i < s.length(); i++) {

            System.out.println(currIndex);

            newString += s.charAt(currIndex);

            if(currRow == 0 || currRow == numRows - 1) {
                currIndex += originalDiff;
            } else { 
                if(isGoingDown) {
                    currIndex += diff;
                    isGoingDown = !isGoingDown;
                } else {
                    currIndex += upperDiff;
                    isGoingDown = !isGoingDown;
                }
            }

            if(currIndex >= s.length()) {
                currRow++;
                diff -= 2;
                upperDiff += 2;
                currIndex = currRow;
                isGoingDown = true;
            }
            if(currRow == numRows) {
                i = s.length();
            }
        }

        return newString;

    }
}

答案 4 :(得分:0)

我的解决方案按照问题中提到的相同方式遍历字符串,最好使字符串数组的大小为numrows,其余部分则按照逻辑中的顺序存储字符串字符,

您可以保留索引,并且当索引为0时(即在开始时),我们必须走到行尾,然后除第一行和最后一行外,每个数组都会有对角线元素。

因此,在遍历到末尾之后,分配index = numrows-2并保存在相应的数组字符串中,然后减小并执行相同的操作,直到index> 0,然后再次遍历到末尾行,并在到达末尾时执行此操作然后从循环中断开。

,然后将所有字符串数组的字符串连接到新的res字符串中。

class Solution {
    public String convert(String s, int n) {
    if(n==1 || n>=s.length())
        return s;
        String[] a = new String[n]; //string array
        int ind=0;    // index for the string array
        boolean flag=true;
        int cnt=0;   //to keep the counter till where we have traversed the string
        while(true && flag)
        {
            if(ind==0)
            {
                for(int i=0;i<n;i++)
                {
                    a[i] += s.charAt(cnt);
                    cnt++;
                    if(cnt==s.length())
                    {
                        flag=false;
                        break;
                    }
                }                 // here it has reached the end so we assign here
                ind = n-2;
            }
            else if(ind>0 && ind<n && flag)
            {
                a[ind] += s.charAt(cnt);
                cnt++;
                if(cnt==s.length())
                    {
                        flag=false;
                        break;
                    }
                ind--;          // to move diagonally up
            }
        }
        String res = new String("");
        for(int i=0;i<a.length;i++)
            {
            // System.out.println(a[i].substring(4));
            res += a[i].substring(4);
        }


        return res;
    }
}

答案 5 :(得分:0)

以下是简单的解决方案。

class Solution:
    def convert(self, s: str, numRows: int) -> str: 
        if numRows <= 1:
            return s
        
        res = ""
        p = numRows * 2 - 2
        
        temp = p
        for i in range(0,numRows):
            index = i
            flag = 0
            while index < len(s):
                res = res + s[index]
                if i == 0 or i == numRows-1:
                    index = index + p
                else:
                    if flag == 0:
                        index = index + temp
                        flag = 1
                    else:
                        index = index + p-temp
                        flag = 0
                        
            temp = temp - 2
            
        return res
相关问题