zoukankan      html  css  js  c++  java
  • Swift一些数据结构题目的编码实现

    题目:在字符串中找出连续最长的数字串,并把这个串的长度返回;如果长度相同,返回最后一个连续字符串

    样例输入
    abcd12345ed125ss123456789
    abcd12345ss54321

    样例输出
    输出123456789,函数返回值9
    输出54321,函数返回值5

     

    函数原型:
       int Continumax(String intputStr,  StringBuffer outputStr)

    输入参数:
       String intputStr  输入字符串

    输出参数:
       StringBuffer outputStr  连续最长的数字串,如果连续最长的数字串的长度为0,应该返回空字符串  

    返回值:
       int 连续最长的数字串的长度

    实现代码:

    func findLongestNum(str:Array<String>){

        var maxLengthNum:Int = 0                        //定义最长数字字符串的长度

        var maxLengthNumStr:Array<String> = []  //用来保持最长字符串

        var nowLengthNum:Int = 0                        //用于储存当前连续数字字符的字符串长度

        var nowLengthNumStr:Array<String> = [] // 用于储存当前连续的数字字符串

     

        for (var i = 0 ; i < str.count ; i++){

            if (str[i] < "9" || str[i] > "0"){              //当前的字符串为数字时

                nowLengthNum++         //当前连续数字字符串长度

                nowLengthNumStr.append(str[i])    // 把当前连续的数字字符串赋予临时的字符串数组中

                if(nowLengthNum > maxLengthNum){  // 当当前的字符串长度大于最大字符串长度时,把当前的字符串长度以及字符串赋予最大连续数字字符串和长度

                    maxLengthNum = nowLengthNum

                    maxLengthNumStr = nowLengthNumStr

                }

            }

            if (str[i] > "9" || str[i] < "0"){         //一旦出现非数字字符串,立即重置临时当前的连续字符串与连续字符串长度

                nowLengthNum = 0

                nowLengthNumStr = []

            }

            

        }

        println(maxLengthNum)

        println(maxLengthNumStr)

        

    }

     

    //验证

    var str2 = ["a","b","c","d","1","2","3","4","5","s","s","2","3","4","4","5","3","4","5","3","4"]

    findLongestNum(str2)

     

    //************************************输出结果*****************************************//

    "10"

    ["2","3","4","4","5","3","4","5","3","4"]

     

  • 相关阅读:
    python的paramiko模块的安装与使用
    python的paramiko模块的安装与使用
    python的paramiko模块的安装与使用
    Python中的getattr()函数详解
    Python中的getattr()函数详解
    Python模块学习——optparse
    Python模块学习——optparse
    Python模块学习——optparse
    pkg_resources----Entry Points为程序提供扩展点
    pkg_resources----Entry Points为程序提供扩展点
  • 原文地址:https://www.cnblogs.com/IOSwang/p/4740682.html
Copyright © 2011-2022 走看看