uva 10716 - Evil Straw Warts Live

来源:互联网 发布:家用电脑远程监控软件 编辑:程序博客网 时间:2024/05/16 08:50

Problem D: Evil Straw Warts Live

A palindrome is a string of symbols that is equal to itself when reversed. Given an input string, not necessarily a palindrome, compute the number of swaps necessary to transform the string into a palindrome. By swap we mean reversing the order of two adjacent symbols. For example, the string "mamad" may be transformed into the palindrome "madam" with 3 swaps:
  • swap "ad" to yield "mamda"
  • swap "md" to yield "madma"
  • swap "ma" to yield "madam"

The first line of input gives n, the number of test cases. For each test case, one line of input follows, containing a string of up to 100 lowercase letters. Output consists of one line per test case. This line will contain the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.

Sample Input

3mamadasflkjaabb

Output for Sample Input

3Impossible2
描述:
判断一个字符串是否可以经过字符交换转化为回文字符串。
方法:
先统计字符串中各个字符的出现的次数和个数是奇数的字符个数。找出字符串的长度L。如果奇数字符大于1个,返回-1.
从左往右遍历字符串(到长度的一半L/2),对每一个字符
如果其个数大于1,则从字对称位置向头遍历,直到找到第一个相同字符,然后把它移动到对称位置。并记录移动次数,相应字符个数减少2。
如果其个数等于1,与下一个字符交换位置,并重新处理该位置的新字符。记录移动次数(+1)。
代码:

0 0
原创粉丝点击