【问题标题】:Can anybody solve this programming challenge? [closed]任何人都可以解决这个编程挑战吗? [关闭]
【发布时间】:2014-08-12 05:32:32
【问题描述】:

任何人都可以使用编程语言 Go 解决以下问题吗?

詹姆斯拿到了他的朋友哈利写给他的一封情书 他的女朋友。作为詹姆斯的恶作剧者,他决定 插手它。他把信中的所有词都改成 回文。

在修改单词的字母时,他遵循两条规则:

  1. 他总是降低字母的值,例如他将“d”更改为 'c',但他没有将'c' 更改为'd'。

  2. 如果他不得不反复 减少一个字母的价值,他可以做到直到字母变成 '一种'。一旦字母被更改为“a”,它就不能再 改变了。

任何字母值的每次减少都算作一次 手术。找出他执行的最小操作数 将给定的字符串转换为回文。

输入格式

第一行包含一个整数T,即数字 的测试用例。接下来的 T 行每行都包含一个字符串。

输出格式

单行包含最小数量 每个测试用例对应的操作。

约束

1 ≤ T ≤ 10 1 ≤ 字符串长度 ≤ 104 所有字符都是 小写。

示例输入

#00 3 abc abcba abcd

样本输出

#00 2 0 4

说明

对于第一个测试用例,ab*c* -> ab*b* -> ab*a*。为了 第二个测试用例,abcba 是一个回文字符串。对于第三次测试 案例,abc*d* -> abc*c* -> abc*b* -> abc*a* = ab*c*a -> ab*b*a。

这个谜题来自 HackerRank.com 我是一个 golang 新手,无法使用该语言解决这个谜题。

【问题讨论】:

标签: go


【解决方案1】:

我认为 Go 编程语言中的解决方案没有什么特别之处。例如,

// The Love-Letter Mystery
// https://www.hackerrank.com/challenges/the-love-letter-mystery

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
)

// palindrome returns the minimum number of operations carried out
// to convert a word into a palindrome.
// A word is a set of lower-case ASCII letters.
func palindrome(word string) (ops int) {
    for i, j := 0, len(word)-1; i < j; i, j = i+1, j-1 {
        n := int(word[i]) - int(word[j])
        if n < 0 {
            n = -n
        }
        ops += n
    }
    return ops
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        t, err := strconv.Atoi(scanner.Text())
        if err != nil {
            fmt.Fprintln(os.Stderr, "reading input:", err)
            t = 0
        }
        for ; t > 0 && scanner.Scan(); t-- {
            fmt.Println(palindrome(scanner.Text()))
        }
        if t > 0 {
            fmt.Fprintln(os.Stderr, "reading input:", io.ErrUnexpectedEOF)
        }
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading input:", err)
    }
}

输入:

3
abc
abcba
abcd

输出:

2
0
4

输入:

3
cba
cbabc
dcba

输出:

2
0
4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2020-05-24
    相关资源
    最近更新 更多