arrays - 查找字符串中字符之间的长度

标签 arrays string algorithm scala line

我有一个从字符和字符串到整数数组的函数。该数组有一个索引,它是该字符在文本中出现的次数内的一个数字,该索引的条目是与文本中出现的前一个字符的距离。如果该字符是换行符,则此函数基本上计算给定字符串的行长度数组。

val func: Char => (String => Array[Int]) = (ch: Char) => (str: String) => {
    var lens: Array[Int] = new Array[Int](20)
    var noCh: Int = 0
    var c: Int = 0 // accumlates till the next character is spotted
    for (i <- 0 until str.length) {
        c += 1
        if (str.charAt(i) == ch) {
            if (noCh>= lens.length) {
                val newlen: Array[Int] = new Array[Int](2*noCh)
                Array.copy(lens,0,newlen,0,noCh)
                lens = newlen
            }
            lens(noCh) = c; c = 0; noCh+= 1
        }
    }
    lens
    }                                         //> func  : Char => (String => Array[Int]) = <function1>
    func('\n')("hello world \n hello wstsadfasdf \n sdlfkjasdf\n")
                                                  //> res2: Array[Int] = Array(13, 20, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                                                  //| 0, 0, 0, 0)

有没有更快的方法来解决这个问题?遍历每个字符似乎很慢,尤其是当您遍历一个非常大的字符串时。

最佳答案

正如其他人所说,需要扫描整个字符串。您还打算如何找到 ch 的出现?但你肯定是在为它制造恶劣的天气,因为它是单线的:

def func(ch:Char)(str:String):Array[Int] =
 str.foldLeft(List(1)){(a,c)=>if(c!=ch) a.head+1::a.tail else 1::a}.tail.reverse.toArray

func('\n')("hello world \n hello wstsadfasdf \n sdlfkjasdf\n")
//> res0: Array[Int] = Array(13, 20, 12)

或者(更简单,虽然在创建字符串数组时效率可能有点低)

def func2(ch:Char)(str:String):Array[Int] = str.split(ch).map(_.length+1)

关于arrays - 查找字符串中字符之间的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802799/

相关文章:

javascript - 根据现有对象数组的几个属性返回新的对象数组

javascript - 在中间添加字符串生成序列号

.net - 寻找有关 .NET 的情感分析算法/工具的信息

java - 并发修改异常——设置数组元素

.net - 将 float 转换为字符串并获取精确值

java - 将数字提取到字符串数组中

C# 判断字符串数组中的某个元素是否在任意位置包含给定的字符串

string - 在 R 中生成子字符串和随机字符串

arrays - 如何快速将字典分配给 AnyObject

javascript - 您的所有断言都通过了吗?