您的位置:首页 > 其它

uva 10716 - Evil Straw Warts Live

2014-02-28 20:08 615 查看

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 apalindrome. By swap we mean reversing the order of two adjacent symbols. For example, the string "mamad" may be transformedinto 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 testcase. This line will contain the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.

Sample Input

3
mamad
asflkj
aabb

Output for Sample Input

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

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: