6. ZigZag Conversion - LeetCode

LeetCode Problems Solutions

question description: 问题描述

//问题截图:


6. ZigZag Conversion - LeetCode_第1张图片
origin.png

//锯齿状


6. ZigZag Conversion - LeetCode_第2张图片
sawtooth.png

Thinking
你们可以自己先考虑一下。

solution with java - Java解决方案

public String convert(String s, int numRows) {


        if (numRows == 1) { //特殊处理,建议单独写在这里,避免后面逻辑复杂
            return s;
        }

        String resultStr = ""; // 结果值


        int keyIndex = 0; //字典的key值,只会是从 0 到 numrows - 1 的值
        boolean israsing = true; // 是否递增 01234321012343210


        Map dict = new HashMap<>();//将传进来的字符串 有规律的保存进字典

        char[] characters = s.toCharArray();
        for (int i = 0 ; i < characters.length ; i ++){

            Character chars = characters[i];

            //确定在第几行
            if (keyIndex == 0) {

                israsing = true;

            }else if (keyIndex == (numRows - 1)) {

                israsing = false;
            }


            String key = keyIndex + "";
            if (dict.get(key) == null) {
                dict.put(key,chars.toString());
            }else{
                dict.put(key,dict.get(key) + chars.toString());
            }



            if (israsing) {
                keyIndex += 1;
            }else{
                keyIndex -= 1;
            }
        }


        for (int j = 0 ; j < numRows ; j ++){
            String index = j + "";
            if (dict.get(index) != null){
                resultStr += dict.get(index);
            }
        }

        return resultStr;

    }

solution with swift - swift解决方案

func convert(_ s: String, _ numRows: Int) -> String {
        
        
        if numRows == 1 { //特殊处理,建议单独写在这里,避免后面逻辑复杂
            return s
        }
        
        var resultStr = "" // 结果值


        var keyIndex = 0 //字典的key值,只会是从 0 到 numrows - 1 的值
        var israsing = true // 是否递增 01234321012343210
        
        var dict = [String:String]() //将传进来的字符串 有规律的保存进字典
        
        for char in s.characters{
            
//            let startIndex = s.index(s.startIndex, offsetBy: multiple * numRows + remainder)
//            let endIndex = s.index(s.startIndex, offsetBy: index + 1)
//            
//            resultStr = s.replacingCharacters(in: startIndex..

你可能感兴趣的:(6. ZigZag Conversion - LeetCode)